halcy / Mastodon.py

Python wrapper for the Mastodon ( https://github.com/mastodon/mastodon/ ) API.
MIT License
867 stars 150 forks source link

[question] Keeping async listener connection active? #357

Closed chickenmuchroom closed 5 months ago

chickenmuchroom commented 9 months ago

Hello, for some reason I cannot keep my bot active when I put run_async as True for stream_user. Is there a method for my bot to stay active and have a asynchronous listener at the same time?

from mastodon import Mastodon
from mastodon.streaming import StreamListener
import asyncio

m = Mastodon(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET",
    access_token=TOKEN,
    api_base_url='https://example.com'
)

print('logged in.')

class Listener(StreamListener):
    def on_notification(self, notification):
        if notification['type'] == 'mention':

            show = notification['status']['visibility']
            if 'hello' in notification['status']['content']:
                m.status_post("Python bot says "Hello" back to you!.", in_reply_to_id=notification['status']['id'], visibility=show)
            else:
                m.status_post("Python bot cannot understand this interaction.", in_reply_to_id=notification['status']['id'], visibility=show)

def main():
    m.stream_user(Listener(), run_async=True, reconnect_async=True)

if __name__ == "__main__":
    main()

I'm very sorry if this is a sloppy question; I've tried searching for information with making Mastodon bot but apparently there isn't much information available.

halcy commented 9 months ago

Hi, if you pass run_async, the call will return (almost) immediately, and start a thread in the background, but if your main thread quits (which it will, because your main function is done), that thread also gets killed. If you want it to run indefinitely, you could have your main thread do something like while True: time.sleep(1000). Alternatively, just don't pass run_async (in that case, you'd have to handle reconnects yourself, though (catch exceptions around the call to stream_user)

halcy commented 5 months ago

closing as likely resolved, feel free to reopen if not