skip to Main Content

I’m trying to make a very simple Telegram Bot in Python that says "Hi" every minute. This is the code so far, but it does not post anything to my telegram.

import requests
import time

bot_token = "insert_token_here"
group_chat_id = "insert_group_chat_id_here"

def send_message(chat_id, text):
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": text
    }
    requests.post(url, data=payload)

while True:
    send_message(group_chat_id, "Hi")
    time.sleep(60)

2

Answers


  1. You can give it a try, but make sure you installed "python-telegram-bot" through pip/pip3.

    import logging
    from telegram import Bot
    from telegram.ext import Updater, CommandHandler, CallbackContext
    from datetime import datetime
    import time
    
    # Set your Telegram Bot Token here
    TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
    
    # Set your chat_id (replace with your chat_id)
    CHAT_ID = "YOUR_CHAT_ID"
    
    # Enable logging
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    # Define the function to send "Hi" message
    def send_hi_message(context: CallbackContext):
        context.bot.send_message(chat_id=CHAT_ID, text="Hi!")
    
    def start(update, context):
        update.message.reply_text('Bot is running!')
    
    def main():
        # Create the Updater and pass it your bot's token
        updater = Updater(token=TOKEN)
    
        # Get the dispatcher to register handlers
        dp = updater.dispatcher
    
        # Register the command handler
        dp.add_handler(CommandHandler("start", start))
    
        # Use the JobQueue to schedule the 'send_hi_message' function every minute
        j = updater.job_queue
        j.run_repeating(send_hi_message, interval=60, first=0)
    
        # Start the Bot
        updater.start_polling()
    
        # Run the bot until you send a signal to stop (Ctrl+C)
        updater.idle()
    
    if __name__ == '__main__':
        main()
    

    Replace "YOUR_TELEGRAM_BOT_TOKEN" and "YOUR_CHAT_ID" with your actual Telegram bot token and chat ID.

    Login or Signup to reply.
  2. To create a simple Telegram bot in Python that sends "Hi" every minute, you can use the python-telegram-bot library. Make sure you have it installed by running:

    pip install python-telegram-bot

    Replace ‘YOUR_BOT_TOKEN’ with the actual token you obtain from BotFather on Telegram

    import logging
    import time
    from telegram import Bot
    from telegram.error import TelegramError
    from telegram.ext import Updater, MessageHandler, Filters
    
    # Set up logging
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    # Replace 'YOUR_BOT_TOKEN' with your actual bot token
    bot_token = 'YOUR_BOT_TOKEN'
    bot = Bot(token=bot_token)
    
    def send_hi(context):
        try:
           context.bot.send_message(context.job.context['chat_id'], text="Hi!")
        except TelegramError as e:
           logger.error(f"Error sending message: {e}")
    
    def start(update, context):
        update.message.reply_text("Hi! I will say 'Hi' every minute.")
    
        # Schedule the job to run every minute
        job_queue = context.job_queue
        job_queue.run_repeating(send_hi, interval=60, first=0, context={'chat_id': update.message.chat_id})
    
    def main():
        # Create the Updater and pass it your bot's token
        updater = Updater(token=bot_token, use_context=True)
    
        # Get the dispatcher to register handlers
        dp = updater.dispatcher
    
        # Register the handlers
        dp.add_handler(MessageHandler(Filters.TEXT & ~Filters.COMMAND, start))
    
        # Start the Bot
        updater.start_polling()
    
        # Run the bot until you send a signal to stop it
        updater.idle()
    
    if __name__ == '__main__':
        main()
    

    Run the script, and your bot will say "Hi" every minute. Keep in mind that you need to start a conversation with your bot on Telegram before it can send messages to you.

    You can also use pyTelegramBotAPI this is more convenient.
    Install it using pip install pyTelegramBotAPI and import is as telebot. For more info checkout my project @ https://github.com/Sanskar-Shimpi/Telegram-Bot

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search