Hi , anyone tried to communicate with a telegram bot using streamlit?
Here is my code :
#telegram_send.send(messages=["Wow that was easy!"])
#connecting and building the session
client = TelegramClient('test_session', api_id, api_hash)**
client.connect()
#in case of script ran first time it will
#ask either to input token or otp sent to
#number or sent or your telegram id
if not client.is_user_authorized():
client.send_code_request(phone)
#signing in the client
input_code = st.text_input('Enter the code')
client.sign_in(phone, input_code)
try:
#receiver user_id and access_hash, use
#my user_id and access_hash for reference
receiver = InputPeerUser(user_id, user_hash)
#sending message using telegram client
client.send_message(receiver, message, parse_mode='html')
except Exception as e:
#there may be many error coming in while like peer
#error, wrong access_hash, flood_error, etc
print(e);
#disconnecting the telegram session
client.disconnect()
The error I am having is
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'.
I’ve seen the “no current event loop” error when doing async stuff, looks like telegram has some docs on writing a coroutine
Using set_event_loop
has helped me in the past (github source)
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
I think this user might be onto something for handling re-runs by including something like st.cache
1 Like
If this helps, here’s an example where I define an asyncio loop at the start of the app if none exists and store it in session_state for future usage. I think this is also how streamit-webrtc manages it
import asyncio
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
if "loop" not in st.session_state:
st.session_state.loop = asyncio.new_event_loop()
asyncio.set_event_loop(st.session_state.loop)
# ... do the Telegram stuff
now I’m wondering if that can be put into experimental_singleton instead but … I doubt it
Have a nice day
Fanilo
2 Likes
Thank you. This solved my problem.
1 Like
Thank you for your kind suggestion. Appreciate it. Have a good day
1 Like
Yeah i’m wondering if the st.cache
actually does much… State seems like an easier place for it per user