MaTok
MaTok

Reputation: 391

Telethon write a message/start a chat after button - bot send message before /start

I'm trying to write an access bot with telethon for telegram.

  1. User added to the group or join with an invite link.
  2. Get restricted and have to push a button.
  3. The bot write a simple captcha message like "1+2=?"
  4. And if it's right, the person gets unrestricted and if wrong, gets kicked out...

Everything works pretty fine but:
If the new joined and user don't write first "/start", the user doesn't get a message from the bot.

Is there any possibility that the person receives the message anyway?

I've read it is not possible to do that somewhere, but there are bots outside how do that?

Upvotes: 2

Views: 2173

Answers (1)

Lonami
Lonami

Reputation: 7086

You can detect when a user joins with events.ChatAction and restrict them from sending messages immediately with client.edit_permissions. In the group, you can let them know with a message with buttons that they have to solve a captcha with the bot in private, which you can react to with 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()

Upvotes: 5

Related Questions