如何在电报机器人 python 代码中立即执行轮询功能?

Jin

我正在尝试运行一个代码,该代码将在某些事件期间自动发送电报轮询,并立即分析答案。

我找到了一个可以实现我想要的示例代码,但我想在运行这段代码时立即执行 self.poll() 而不是等待用户输入“/poll”。我还不熟悉这种编码风格,似乎无法找到一种方法……有人可以帮我吗?

问题主要在代码的第 83 行。(见该部分的评论)

from telegram import (
    Poll,
    ParseMode,
    KeyboardButton,
    KeyboardButtonPollType,
    ReplyKeyboardMarkup,
    ReplyKeyboardRemove,
    Update,
)
from telegram.ext import (
    Updater,
    CommandHandler,
    PollAnswerHandler,
    PollHandler,
    MessageHandler,
    Filters,
    CallbackContext,
)
from telegram import Bot
import time

class TelegramBot:
    def __init__(self, api_key, chat_id):
        self.api_key = api_key
        self.chat_id = chat_id
        self.options = ['0', '1', '2']

    def send_message(self, message):
        self.tel = Bot(token=self.api_key)
        self.tel.sendMessage(self.chat_id, message)

    def poll(self, update: Update , context: CallbackContext) -> None:
        """Sends a predefined poll"""
        options = self.options
        message = context.bot.send_poll(
            update.effective_chat.id,
            "What is the number?",
            options,
            is_anonymous=False,
            allows_multiple_answers=False
        )

        # Save some info about the poll the bot_data for later use in receive_poll_answer
        payload = {
            message.poll.id: {
                "options": options,
                "message_id": message.message_id,
                "chat_id": update.effective_chat.id,
                "answers": 0,
            }
        }
        context.bot_data.update(payload)

    def receive_poll_answer(self, update: Update, context: CallbackContext) -> None:
        """Summarize a users poll vote"""
        answer = update.poll_answer
        poll_id = answer.poll_id
        try:
            options = context.bot_data[poll_id]["options"]
        # this means this poll answer update is from an old poll, we can't do our answering then
        except KeyError:
            return
        selected_options = answer.option_ids
        answer_string = ""
        for option_id in selected_options:
            if option_id != selected_options[-1]:
                answer_string += options[option_id] + " and "
            else:
                answer_string += options[option_id]

        context.bot_data[poll_id]["answers"] += 1
        # Close poll after 50 participants voted
        if context.bot_data[poll_id]["answers"] == 50:
            context.bot.stop_poll(
                context.bot_data[poll_id]["chat_id"], context.bot_data[poll_id]["message_id"]
            )

    def run(self) -> None:
        """Run bot."""
        # Create the Updater and pass it your bot's token.
        updater = Updater(self.api_key)
        dispatcher = updater.dispatcher
        dispatcher.add_handler(CommandHandler('poll', self.poll)) # <---- I want to run self.poll right here when I execute this whole function run(). Currently it's only possible to trigger it by user input command '/poll'
        dispatcher.add_handler(PollAnswerHandler(self.receive_poll_answer))
        # Start the Bot
        updater.start_polling()
        updater.idle()

telegram_bot = TelegramBot('api_key', 'chat_id')
telegram_bot.send_message('/poll') # I tried sending /poll using the bot itself before executing run(), but it does not seem to register bot messages
telegram_bot.run()
CallMeStag

poll是一个处理程序回调,即工作它需要一个传入updatecontext与该更新相关联的。更准确地说,您的poll函数使用 中chat_id包含的update将消息发送到,context.bot_data将数据存储在context.bot其中并向 Telegram 发出请求。您可以做的是将update- 和 -context相关的逻辑分解为另一个函数,例如


def poll(self, chat_id, bot, bot_data):
    # what `poll` currently does but replace `update.effective_chat.id` with `chat_id`
   # and `context.{bot_data, bot}` with `bot_data`/`bot`

def poll_callback(self, update, context):
    self.poll(update.effective_chat.id, context.bot, context.bot_data)

(请注意,如果您例如存储self.bot = updater.bot其中会更容易run- 那么您不需要传递botpoll但可以使用self.bot。)

然后你可以调用poll你的run函数

self.poll(some_chat_id, dispatcher.bot_data)

请注意,context.bot_data它始终与 相同的对象dispatcher.bot_data,这就是为什么它有效。


免责声明:我目前是 python-telegram-bot

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

电报机器人:如何使用botFather删除命令

电报机器人,如何请求用户输入?

电报机器人:如何获得内联结果

python-电报机器人sendMessage在特定日期

如何删除电报机器人说明?

如何在电报机器人python中检测gif

如何安排电报机器人发送消息?

在用户对电报机器人进行有效答复之前,如何重复执行功能和处理程序?

如何在Discord机器人项目中运行额外的Python代码

电报机器人不断回复,而不是执行以下代码(使用了webhook)

电报机器人:自定义键盘发送代码

如何更改电报机器人消息中的图片?

如何使用python在电报机器人中创建自定义键盘?

带有 python-telegram-bot 库的电报机器人

电报机器人:使用 python 发送照片方法

Python电报机器人持久化与谷歌应用引擎

python中的电报机器人代理

我想用 python 为电报机器人编写一个计时器。机器人从用户的 msg (str) 中获取“时间”。如何将“时间”从 msg 转换为 (int) 类型?

删除电报机器人发送的外发消息(电报,python)

如何用照片让电报机器人回复?

用户响应后是否有删除 InlineKeyboardMarkup 的功能?(蟒蛇电报机器人)

python电报机器人得到下一个问题我需要输入任何东西

Python电报机器人,转发编辑的消息

使用 python-telegram-bot 包向电报机器人发送语音命令

如何识别此回复是在哪条消息上?Python 电报机器人

requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): # python 电报机器人使用 pytelegrambotapi 和 Tor

如何使用 python 在电报机器人中发送数据帧表

解析(抓取)网页时如何将“display:flex”更改为“display:none”?| Python(电报机器人)| 硒

如何在机器人消息电报机器人之后从用户那里获取消息更新