use hikari instead of discord.py

Running async/awaitable functions inside discord.py's event loop was
very difficult. Hikari didn't have this problem.
This commit is contained in:
Vineet K 2024-01-14 23:16:42 -05:00
parent c2d1d70cd1
commit 1cc61d85c3
2 changed files with 17 additions and 22 deletions

37
main.py
View File

@ -1,10 +1,11 @@
import asyncio, json, os, discord import asyncio, json, os
import hikari
import mautrix.client import mautrix.client
intents = discord.Intents.default() dclient = hikari.GatewayBot(
intents.message_content = True token=os.getenv("DISCORD_TOKEN"),
intents=(hikari.Intents.MESSAGE_CONTENT|hikari.Intents.GUILD_MESSAGES)
dclient = discord.Client(intents=intents) )
mclient = mautrix.client.ClientAPI( mclient = mautrix.client.ClientAPI(
os.getenv("MATRIX_USERID"), os.getenv("MATRIX_USERID"),
base_url=os.getenv("MATRIX_HOMESERVER"), base_url=os.getenv("MATRIX_HOMESERVER"),
@ -14,8 +15,6 @@ mclient = mautrix.client.ClientAPI(
rooms = {1196201613132574733: "!eChKdzVweNTyHctaKQ:wired.rehab"} rooms = {1196201613132574733: "!eChKdzVweNTyHctaKQ:wired.rehab"}
async def matrix_init(): async def matrix_init():
joined = await mclient.get_joined_rooms()
print(joined)
for room in rooms.values(): for room in rooms.values():
try: try:
await mclient.join_room_by_id(room) await mclient.join_room_by_id(room)
@ -25,25 +24,21 @@ async def matrix_init():
exit(1) exit(1)
joined = await mclient.get_joined_rooms() joined = await mclient.get_joined_rooms()
print(joined) print(joined)
for room in joined:
await mclient.send_message(room, '{"body":"joined","msgtype":"m.text"}')
task = asyncio.get_event_loop().create_task(matrix_init()) task = asyncio.get_event_loop().create_task(matrix_init())
asyncio.get_event_loop().run_until_complete(task) asyncio.get_event_loop().run_until_complete(task)
@dclient.event @dclient.listen()
async def on_ready(): async def on_message(event: hikari.GuildMessageCreateEvent) -> None:
print(f"Logged in as {dclient.user}") if not event.content:
return
@dclient.event chanid = event.channel_id
async def on_message(message): if chanid in rooms.keys():
if message.channel.id in rooms.keys(): print(f"<{event.message.author.global_name}> {event.content}")
print(f"<{message.author.global_name}> {message.content}")
content = {} content = {}
content['body'] = f"<message.author.global_name> {message.content}" content['body'] = f"<{event.message.author.global_name}> {event.content}"
content['msgtype'] = "m.text" content['msgtype'] = "m.text"
await mclient.send_message(rooms[chanid], json.dumps(content))
print(json.dumps(content)) dclient.run()
await mclient.send_message(rooms[message.channel.id], json.dumps(content))
dclient.run(os.getenv("DISCORD_TOKEN"))

View File

@ -1,2 +1,2 @@
discord.py hikari
mautrix mautrix