-1

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. 2 websocket connection image

How can I do that?

OmerFI
  • 106
  • 1
  • 1
  • 7

1 Answers1

0

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()
OmerFI
  • 106
  • 1
  • 1
  • 7