电报机器人可以阻止特定用户吗?

Can a telegram bot block a specific user?

我有一个电报机器人,它针对任何收到的消息在服务器中运行一个程序并将其结果发回。但有个问题!如果用户向我的机器人发送太多消息(垃圾邮件),它会使服务器非常繁忙!
有没有什么办法可以屏蔽那些一秒钟发了5条以上消息就再也收不到的人? (使用电报 api!!)

首先我要说的是Telegram Bot API本身没有这样的能力,所以你需要自己实现它,你需要做的就是:

  1. 计算用户在一秒钟内发送的消息数,如果没有数据库,这将不会那么容易。但是,如果你有一个名为 Black_List 的 table 数据库,并将所有消息及其发送时间保存在另一个 table 中,你将能够计算通过一个特定的 ChatID 在预定义的时间段内(在您的情况下;1 秒)并检查计数是否大于 5,如果答案是肯定的您可以将该 ChatID 插入 Black_List table.
  2. 每次机器人收到一条消息时,它必须 运行 查询数据库以查看发件人的 chatID 是否存在于 Black_List table 中。如果它存在,它应该继续它自己的工作并忽略该消息(或者甚至它可以向用户发送警告说:"You're blocked." 我认为这可能很耗时)。

请注意,据我所知,目前的电报机器人 API 没有停止接收消息的功能,但正如我上面提到的,您可以忽略来自垃圾邮件发送者的消息。

In order to save time, You should avoid making a database connection every time the bot receives an update(message), instead you can load the ChatIDs that exist in the Black_List to a DataSet and update the DataSet right after the insertion of a new spammer ChatID to the Black_List table. This way the number of the queries will reduce noticeably.

我是这样实现的:

# Using the ttlcache to set a time-limited dict. you can adjust the ttl.
ttl_cache = cachetools.TTLCache(maxsize=128, ttl=60)


def check_user_msg_frequency(message):
    print(ttl_cache)
    msg_cnt = ttl_cache[message.from_user.id]
    if msg_cnt > 3:
        now = datetime.now()
        until = now + timedelta(seconds=60*10)
        bot.restrict_chat_member(message.chat.id, message.from_user.id, until_date=until)
        

def set_user_msg_frequency(message):
    if not ttl_cache.get(message.from_user.id):
        ttl_cache[message.from_user.id] = 1
    else:
        ttl_cache[message.from_user.id] += 1

通过以上这些功能,您可以记录某个用户在一段时间内发送了多少条消息。如果用户发送的消息超过预期,他将被限制。

然后,您调用的每个处理程序都应该调用这两个函数:

@bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
    set_user_msg_frequency(message)
    check_user_msg_frequency(message)

我正在使用 pyTelegramBotAPI 这个模块来处理。