Issue
I want to make a discord bot. This application will connect to a websocket server (for example ws://example.com) and when it receives a message from that connection it should process the message (like parse json and format the output message) and send it to a channel via discord.py.
How can I do that?
Solution
Answer https://stackoverflow.com/a/53024361/14892434 helped me solve the issue.
What I need was to create two separate coroutines and run them in the same loop.
Example code:
import discord
import asyncio
import json
import websockets
intents = discord.Intents.default()
intents.message_content = True
CHANNEL_ID = 555555555 # Replace with your desired channel ID
BOT_TOKEN = "" # Replace with your Discord bot token
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"Logged in as {client.user.name} (ID: {client.user.id})")
async def handle_message(message):
# Parse the JSON message
data = json.loads(message)
# Format the message as a Discord message
formatted_message = f'**{data["message"]}**'
# Get the channel to send the message to
channel = client.get_channel(CHANNEL_ID)
# Send the message
await channel.send(formatted_message)
async def listen():
print("Connecting to WebSocket server...")
async with websockets.connect(
"wss://example.com/ws/", extra_headers={"Origin": "https://example.com"}
) as websocket:
while True:
message = await websocket.recv()
await handle_message(message)
async def start():
print("Starting Discord client...")
# Start the Discord client
await client.start(BOT_TOKEN)
loop = asyncio.get_event_loop()
loop.create_task(start())
loop.create_task(listen())
loop.run_forever()
Answered By - OmerFI
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.