为 Telegram 提及机器人编写 Python 脚本

问题描述 投票:0回答:1

我已在 Windows 8.1 32 位中安装了最新版本的 Python。我创建了一个 Telegram 机器人。我还为我的机器人编写了一个脚本。我已经安装了 pip、Telegram、Python Telegram bot 以及运行我的 telegram bot 所需的其他程序。

这是我为 Telegram 机器人编写的代码:

import logging
from telegram import Update

# from telegram.update import Update

from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext, Filters


logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

TOKEN = 'I removed it for now'

# Initialize the Updater
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher

# Command handler
def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text("Hello! I am your mention bot. Use @everyone to mention all members.")

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

# Mention handler
def handle_mentions(update: Update, context: CallbackContext) -> None:
    message_text = update.message.text
    if "@everyone" in message_text:
        chat_id = update.message.chat_id
        
        # Get the list of all members in the group
        all_members = context.bot.get_chat_members(chat_id)
        
        # Prepare the mention message
        mention_message = " ".join([f"@{member.user.username}" for member in all_members if member.user.username])
        if mention_message:
            mention_message = f"Mentioning all members: {mention_message}"
        else:
            mention_message = "No active members to mention."
        
        # Send the mention message
        context.bot.send_message(chat_id, mention_message, reply_to_message_id=update.message.message_id)

mention_handler = MessageHandler(Filters.text & ~Filters.command, handle_mentions)
dispatcher.add_handler(mention_handler)

# Start the bot
updater.start_polling()

# Run the bot until you press Ctrl-C
updater.idle()


每当我尝试通过命令

cd c:\python\bot\python mention_bot.py
运行这些保存为提及机器人.py 的脚本时,它总是向我显示此错误:

C:\Python\bot>python mention_bot.py Traceback (most recent call last):
File "C:\Python\bot\mention_bot.py", line 2, in <module>
from telegram import Update
ImportError: cannot import name 'Update' from 'telegram' (C:\Python\Lib\site-pa kages\telegram\_____init__.py>

我怎样才能摆脱这个错误?

python telegram-bot python-telegram-bot
1个回答
0
投票

我已经安装了电报

这就是问题所在。运行

pip uninstall telegram
卸载 telegram 库,然后再次运行 pip install python-telegram-bot。


免责声明:我目前是

python-telegram-bot
的维护者。

© www.soinside.com 2019 - 2024. All rights reserved.