简体   繁体   中英

Send message from bot to self with telethon

I'm trying to send a message to myself using a Telegram bot I have created, and I got the values from https://my.telegram.org as well as the BotFather.

import telebot
from telethon.sync import TelegramClient


def telegram_setup():
    api_id = 12345678
    api_hash = 'X'
    token = 'X'
    phone = '+111'
    client = TelegramClient('session', api_id, api_hash)
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))
    return client


def send_message(client, message):
    try:
        entity = client.get_entity('username')
        client.send_message(entity, message, parse_mode='html')
    except Exception as e:
        print(e)
    client.disconnect()


if __name__ == "__main__":
    client = telegram_setup()
    message = "test"
    send_message(client, message)

The first time I ran this, it sent me a message asking for a code which I supplied. Running it again caused "test" to appear under "Saved Messages" in Telegram, rather than coming from my bot.

Any idea what's causing this or how to resolve it?

Thanks.

EDIT: I realised I'm not using token anywhere, but I'm not sure where it goes.

The bot token is required in client.start() as bot_token ( bot_token = "token" ), if what you do is a bot, your phone is not needed.

Edit: You made a userbot, not a bot.

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