Telethon 在按钮后写消息/开始聊天 - 机器人在/开始之前发送消息

M T*_*ken 2 python telegram telegram-bot telethon

我正在尝试编写一个带有 telethon for telegram 的访问机器人。

  1. 用户已添加到群组或通过邀请链接加入。
  2. 受到限制,必须按下按钮。
  3. 机器人会编写一条简单的验证码消息,例如“1+2=?”
  4. 如果是对的,这个人就不受限制,如果错了,就会被踢出去……

一切都工作得很好,但是:
如果新加入的用户没有先写“/start”,则用户不会从机器人收到消息。

该人是否有可能收到该消息?

我读过在某个地方不可能做到这一点,但是外面有机器人怎么办?

Lon*_*ami 5

您可以检测用户何时加入events.ChatAction并限制他们立即使用 发送消息client.edit_permissions。在群组中,您可以通过带有按钮的消息让他们知道他们必须私下使用机器人解决验证码,您可以通过 做出反应events.Message

from telethon import TelegramClient, Button, events

bot = TelegramClient(...)

async def main():
    async with bot:
        # Needed to find the username of the bot itself,
        # to link users to a private conversation with it.
        me = await bot.get_me()

        @bot.on(events.ChatAction)
        async def handler(event):
            if event.user_joined:
                # Don't let them send messages
                await bot.edit_permissions(event.chat_id, event.user_id, send_messages=False)

                # Send a message with URL button to start your bot with parameter "captcha"
                url = f'https://t.me/{me.username}?start=captcha'
                await event.reply(
                    'Welcome! Please solve a captcha before talking',
                    buttons=Button.url('Solve captcha', url))

        # Detect when people start your bot with parameter "captcha"
        @bot.on(events.NewMessage(pattern='/start captcha'))
        async def handler(event):
            # Make them solve whatever proof you want here
            await event.respond('Please solve this captcha: `1+2 = ?`')
            # ...more logic here to handle the rest or with more handlers...
    
        await bot.run_until_disconnected()
Run Code Online (Sandbox Code Playgroud)