建立一个电报频道机器人,它将私下向新用户发送欢迎消息

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

我刚刚开始使用Python。我正在尝试建立一个电报频道机器人,它将私下向新用户发送欢迎消息。其他用户不应该收到这些消息的垃圾邮件,因此我希望机器人仅将其发送给新用户。

每次我运行我的代码时,它都会出现一个错误,我花了几个小时试图弄清楚。有人可以帮忙吗?我想修正这个错误。如果有人可以指导我,我将不胜感激

这里是错误消息:NameError:名称“Filters”未定义。您指的是:“过滤器”吗?

这是我的代码

import telegram

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

# Define a function to send the welcome message
def welcome(update: telegram.Update, context: CallbackContext):
user = update.message.from_user
chat_id = update.message.chat_id

# Customize your welcome message here
welcome_message = f"Hello {user.first_name}! Welcome to our channel. Here is a link to the    ebook: [https://www.example.com]"

# Send the welcome message privately to the user
context.bot.send_message(chat_id=chat_id, text=welcome_message)


def main():
# Initialize the Telegram Bot
bot = telegram.Bot(token="xxxxx")
updater = Updater(bot, update_queue=None)

# Create a new filter that matches new users
new_user_filter = Filters.new_chat_members()

# Create a command handler to trigger the welcome message
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("welcome", welcome))

# Add the new user filter to the command handler
dispatcher.add_handler(new_user_filter, welcome)

# Start the bot
updater.start_polling()
updater.idle()

if __name__ == "__main__":
main()
python-3.x telegram-bot python-telegram-bot
1个回答
0
投票

您需要从

filters
导入
telegram.ext

首先将

filters
添加到您的
from telegram.ext
行:

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

然后对于

NEW_CHAT_MEMBERS
过滤器,使用:

# Create a new filter that matches new users
new_user_filter = filters.StatusUpdate.NEW_CHAT_MEMBERS
© www.soinside.com 2019 - 2024. All rights reserved.