Closed HuXinjing closed 5 months ago
Hi @HuXinjing ,
sorry it took me so long to respond to you. I suppose this is no longer relevant, but for the record: you need the instance and there are various ways how to make it available from within the callback. This is a hopefully straightforward (even if not ideal) example:
import asyncio
import random
from rocketchat_async import RocketChat
class Bot:
def __init__(self, rc: RocketChat):
self.rc = rc
def handle_message(self, channel_id, sender_id, msg_id, thread_id,
msg, qualifier):
if sender_id != self.rc.user_id:
asyncio.create_task(self.rc.send_message("Accepted.", channel_id))
async def run(self):
for channel_id, channel_type in await self.rc.get_channels():
await self.rc.subscribe_to_channel_messages(channel_id,
self.handle_message)
await self.rc.run_forever()
async def main(address, username, password):
while True:
try:
rc = RocketChat()
await rc.start(address, username, password)
bot = Bot(rc)
await bot.run()
except (RocketChat.ConnectionClosed,
RocketChat.ConnectCallFailed) as e:
print(f'Connection failed: {e}. Waiting a few seconds...')
await asyncio.sleep(random.uniform(4, 8))
print('Reconnecting...')
asyncio.run(main('ws://localhost:3000/websocket', 'varel.bot', 'jahoda'))
I found send_message demend a RocketChat object as an input parameter, however, I couldn't get a 'self' from subscribe_to_channel_messages. So could I call send_message in callback of subscribe_to_channel_messages without 'self'?