getting messages from telegram channels - python

3.6k views Asked by At

i want to develop a bot in telegram with python. i don't know getUpdates can help me or not? or there is any method for doing it. i want to get information(text,pic,link...) of messages from telegram channels. i don't want to do any function inside channels(edit, new post...) so i don't have to be admin of channels. actually i found a bot that can do this(@junction_bot) but i can`t found out how!!?? what syntax i should use? i tried getUpdates method, it should work?

2

There are 2 answers

2
Sean Wei On

Your bot need Channel Administrator permission to receive messages, and you will get channel_post in update, not message

0
Иван On

Url : https://api.telegram.org/bot<TOKEN>/getUpdates

Example on python for get last chat_id and message

URL = 'https://api.telegram.org/bot' + token + '/'
global last_update_id
last_update_id = 0

def get_updates():
    url = URL + 'getupdates'
    r = requests.get(url)
    return r.json()

def get_message():
    data = get_updates()

    last_object = data['result'][-1]
    current_update_id = last_object['update_id']

    global last_update_id
    if last_update_id != current_update_id:
        last_update_id = current_update_id

        chat_id = last_object['message']['chat']['id']
        message_text = last_object['message']['text']
        message = {
        'chat_id': chat_id, 
        'text': message_text
                }   
        return message['chat_id'], message['text']
    return '0', '0'

also u can formate a json dump and take data from updates.json

def format_json_dump():
    data = get_updates()
    with open('updates.json', 'w+') as file:
        json.dump(data, file, indent = 2, ensure_ascii=False)