简体   繁体   中英

How can i force the Telegram Bot to write to the user first (aiogram)?

I'm trying to send welcome message to newcomers to the channel via the bot using Aiogram. However, my bot can't find the chat with the user if he has not started a conversation with the bot before. Are there any solutions of this problem?

I have already managed to handle newcomers and add ids to the db, but

`

@router.chat_member(ChatMemberUpdatedFilter(member_status_changed=(KICKED | LEFT | RESTRICTED)
                                            >>
                                            (ADMINISTRATOR | CREATOR | MEMBER)))
async def on_user_join(event: ChatMemberUpdated):
    with grpc.insecure_channel('') as channel:
        stub = sub_unsub_pb2_grpc.SubscribtionServiceStub(channel)
        timestamp = timestamp_pb2.Timestamp()
        timestamp.FromDatetime(datetime.now(tz=timezone.utc))
        request = sub_unsub_pb2.SubUnsubEvent(
            id=str(event.new_chat_member.user.id),
            channelId=str(event.chat.id),
            time=timestamp,
            subStatus='join'
        )

        response = sub_unsub_pb2.EventResponse()
        stub.TriggerEvent(request)

`

But when I try to send a message, the error chat not found is thrown. `

    await support_bot.send_message(
        user_id,
        f'Welcome to the channel!'
    )

`

Solutions to this problem:

  • Is to have the bot transfer a message to the user as soon as their ID is added to the database. This way, the user will have started a discussion with the bot, and the bot will be capable of finding the chat when you try to send the welcome message.
  • Is to use the start command, so that new users can initiate the discussion with the bot by sending /start command. Also, in the start command handler, you can check whether the user is a new member and send a welcome message.
  • Check the user's presence in the channel by using the get_chat_member method of the bot, which returns a ChatMember object. If the status attribute of this object isChatMember.CHAT_MEMBER_STATUS_LEFT , then the user isn't a member of the channel anymore and you shouldn't send the message.
  • Use the message event to listen for all messages transferred by the user in the channel and check if the user is new or not and send the welcome message accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM