Python Telegram bot doesn’t start running at all.

huangapple go评论64阅读模式
英文:

Python Telegram bot doesn't start running at all

问题

我是一个Python初学者,尝试使用python-telegram-bot库创建一个Telegram定时器机器人,并使用我在网上找到的一些代码片段。然而,当我尝试运行代码时,机器人似乎根本没有开始运行。我已经仔细检查了我是否使用了正确的API令牌,并且机器人被授权访问我的Telegram帐户。

尽管我努力了,但我没有收到任何错误或异常消息。我尝试在不同的机器上运行脚本,但结果始终相同。

有人能提出可能导致这个问题的原因吗?我作为一个初学者可能犯了什么常见的错误,可能会阻止机器人启动?我应该如何调试代码以找出出了什么问题?任何帮助将不胜感激!

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import datetime, time

# 用你的机器人令牌替换YOUR_TOKEN_HERE
bot = telegram.Bot(token='[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]')
updater = Updater(token='[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]', use_context=True)
dispatcher = updater.dispatcher

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Hi! I'm a bot that can help you schedule messages in your Telegram channel. To get started, please enter your message or attachment:")

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

# 其他代码...

updater.start_polling()

我尝试了以下方法:

  • 再次检查了我是否使用了正确的API令牌,并且机器人被授权访问我的Telegram帐户。
  • 在不同的机器上运行脚本,以排除任何与硬件相关的问题。
  • 尝试在代码的各个部分添加print()语句,以查看脚本是否正在执行。

尽管我努力了,但机器人似乎仍然没有开始运行。我没有收到任何错误或异常消息,所以很难准确找出问题出在哪里。

理想情况下,我期望看到机器人开始运行,并能够通过Telegram应用程序与其进行交互。

英文:

I am a Python beginner trying to create a Telegram scheduler bot using the python-telegram-bot library and some code snippets I found online. However, when I try to run the code, the bot doesn't seem to start running at all. I have double-checked that I am using the correct API token and that the bot is authorized to access my Telegram account.

Despite my efforts, I am not getting any error or exception messages. I have tried running the script on different machines, but the result is always the same.

Can anyone suggest what might be causing this issue? Are there any common mistakes I might have made as a beginner that could be preventing the bot from starting? How can I go about debugging the code to figure out what's going wrong? Any help would be greatly appreciated!

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import datetime, time

# replace YOUR_TOKEN_HERE with your bot's token
bot = telegram.Bot(token='[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]')
updater = Updater(
    token='[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]', use_context=True)
dispatcher = updater.dispatcher

    def start(update, context):
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Hi! I'm a bot that can help you schedule messages in your Telegram channel. To get started, please enter your message or attachment:")


start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)


def message_handler(update, context):
    context.user_data['message'] = update.message.text
    # or use update.message.photo or update.message.document to handle attachments
    context.bot.send_message(
        chat_id=update.effective_chat.id, text="Got it! Do you want to add a caption?")


message_handler_handler = MessageHandler(Filters.text, message_handler)
dispatcher.add_handler(message_handler_handler)


def caption_handler(update, context):
    context.user_data['caption'] = update.message.text
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Great! Now, do you want to send the message every day at a specific time, or just once?")


caption_handler_handler = MessageHandler(Filters.text, caption_handler)
dispatcher.add_handler(caption_handler_handler)


def frequency_handler(update, context):
    if update.message.text.lower() == "once":
        # handle one-time message sending
        pass
    elif update.message.text.lower() == "recurring":
        context.user_data['recurring'] = True
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Got it! What time do you want to send the message every day? (format: HH:MM)")
        # add a message scheduler to send the message every day at the specified time
    else:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="I'm sorry, I didn't understand that. Please enter 'once' or 'recurring'.")
        return


frequency_handler_handler = MessageHandler(Filters.text, frequency_handler)
dispatcher.add_handler(frequency_handler_handler)


def time_handler(update, context):
    try:
        send_time = datetime.strptime(update.message.text, '%H:%M').time()
        context.user_data['send_time'] = send_time
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Thanks! Lastly, please enter the channel ID where you want to send the message.")
    except ValueError:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Oops! That's an invalid time format. Please enter the time in HH:MM format.")
        return


time_handler_handler = MessageHandler(Filters.text, time_handler)
dispatcher.add_handler(time_handler_handler)


def channel_handler(update, context):
    context.user_data['channel_id'] = update.message.text
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Got it! Your message has been scheduled to be sent.")
    # add code to schedule the message to be sent to the specified channel at the specified time


channel_handler_handler = MessageHandler(Filters.text, channel_handler)
dispatcher.add_handler(channel_handler_handler)


def view_messages(update, context):
    # add code to retrieve and display stored messages

    def edit_message(update, context):
        # add code to retrieve and edit a specific stored message

        view_messages_handler = CommandHandler('view_messages', view_messages)
        edit_message_handler = CommandHandler('edit_message', edit_message)
        dispatcher.add_handler(view_messages_handler)
        dispatcher.add_handler(edit_message_handler)

    updater.start_polling()

I have tried the following:

  • Double-checked that I am using the correct API token and that the bot is authorized to access my Telegram account.
  • Run the script on different machines to rule out any hardware-related issues.
  • Tried adding print() statements in various parts of my code to see if the script is executing at all.

Despite my efforts, the bot still doesn't seem to start running. I am not getting any error or exception messages, so it's difficult to pinpoint where exactly the issue might be.

Ideally, I was expecting to see the bot start running and to be able to interact with it via the Telegram app.

答案1

得分: 0

您的缩进看起来不正确。尝试这样做:

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import datetime, time

# 用你的机器人令牌替换YOUR_TOKEN_HERE
bot = telegram.Bot(token="[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]")
updater = Updater(token="[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]", use_context=True)
dispatcher = updater.dispatcher

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Hi! I'm a bot that can help you schedule messages in your Telegram channel. To get started, please enter your message or attachment:")

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

# ... (保持其余代码不变)

def view_messages(update, context):
    # 添加代码以检索和显示存储的消息
    pass

def edit_message(update, context):
    # 添加代码以检索和编辑特定的存储消息
    pass

view_messages_handler = CommandHandler('view_messages', view_messages)
edit_message_handler = CommandHandler('edit_message', edit_message)
dispatcher.add_handler(view_messages_handler)
dispatcher.add_handler(edit_message_handler)

updater.start_polling()

在提供的代码中,updater.start_polling() 永远不会执行,因为它位于一个从未调用的函数体内。

英文:

You indentation looks off. Try this:

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from datetime import datetime, time

# replace YOUR_TOKEN_HERE with your bot's token
bot = telegram.Bot(token="[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]")
updater = Updater(
    token="[REMOVED BOT TOKEN BUT CAN CONFIRM IT'S CORRECT]", use_context=True)
dispatcher = updater.dispatcher

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Hi! I'm a bot that can help you schedule messages in your Telegram channel. To get started, please enter your message or attachment:")

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

# ... (keep the rest of your code the same)

def view_messages(update, context):
    # add code to retrieve and display stored messages
    pass

def edit_message(update, context):
    # add code to retrieve and edit a specific stored message
    pass

view_messages_handler = CommandHandler('view_messages', view_messages)
edit_message_handler = CommandHandler('edit_message', edit_message)
dispatcher.add_handler(view_messages_handler)
dispatcher.add_handler(edit_message_handler)

updater.start_polling()

In the code provided, updater.start_polling() will never execute, because it lives in a function body of a function that's never called.

huangapple
  • 本文由 发表于 2023年3月31日 21:19:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定