S
S
spamNedge2020-06-02 14:26:07
Python
spamNedge, 2020-06-02 14:26:07

How to pass the response of the mail parsing function to the telegram bot in python?

There is a function to receive new mail from gmail using the imaplib library:

import email
import imaplib
import config

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(config.gmail_log, config.gmail_pass)
mail.select("INBOX")

def loop():

    mail.select("INBOX")
    n = 0
    (retcode, messages) = mail.search(None, '(UNSEEN)')
    if retcode == 'OK':
        for num in messages[0].split():
            n = n + 1
            typ, data = mail.fetch(num, '(RFC822)')
            for respone_part in data:
                if isinstance(respone_part, tuple):
                    original = email.message_from_string('respone_part[1]')
                    print(original['From'])
                    data = original['Subject']
                    print(data)
                    typ, data = mail.store(num, '+FLAGS', '\\Seen')


if __name__ == '__main__':
    try:
        while True:
            loop()
    finally:
        print("Thanks")


In addition to the function, there is a primitive telegram bot on the Telegram Bot API, which constantly only needs to transmit its response to the user. How can I implement such a function for a bot? All my attempts resulted in a single call to the function and, of course, getting null (
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-06-02
@spamNedge

1) the function must return something, add return data e.g.
2) from a bot, import a module with a mail check function from module_name import loop , is there a better name for the function?
3) add the check_email function in the bot , which periodically pulls the mail check function - loop

from time import sleep


def check_email():
    while True:
        mails = loop()
        if mails:
            for mail in mails:
                bot.send_message(admin_id, mail)
        sleep(60)

4) in the bot, make a call to the check_email function in a separate thread, like this
from threading import Thread

Thread(target=check_email, args=()).start()

5) the bot can only send str , this applies to return data if, for example, a tuple is returned there .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question