Skip to content

Commit

Permalink
Update discord_bot.py
Browse files Browse the repository at this point in the history
  • Loading branch information
oldnapalm committed Oct 26, 2024
1 parent be60f51 commit 21dcd10
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions discord_bot.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
import asyncio
import json
import aiohttp
import os
import threading
import time

from configparser import ConfigParser

import discord
import requests

import zwift_offline


class DiscordBot(discord.Client):
def __init__(self, intents, channel, welcome_msg, help_msg):
discord.Client.__init__(self, intents=intents)
self.channel = channel
self.channel_id = channel
self.welcome_msg = welcome_msg
self.help_msg = help_msg

async def on_ready(self):
self.channel = self.get_channel(self.channel)
self.channel = self.get_channel(self.channel_id)

async def on_member_join(self, member):
if self.welcome_msg:
Expand Down Expand Up @@ -67,23 +65,24 @@ async def starter(self):
def run(self):
try:
self.loop.run_until_complete(self.starter())
except BaseException:
time.sleep(5)
except Exception as exc:
print('DiscordThread exception: %s' % repr(exc))

async def webhook_send(self, message, sender):
async with aiohttp.ClientSession() as session:
await discord.Webhook.from_url(self.webhook, session=session).send(message, username=sender)

def send_message(self, message, sender_id=None):
if sender_id is not None:
profile = zwift_offline.get_partial_profile(sender_id)
sender = profile.first_name + ' ' + profile.last_name
else:
sender = 'Server'
data = {}
data["content"] = message
data["username"] = sender
requests.post(self.webhook, data=json.dumps(data), headers={"Content-Type": "application/json"})
asyncio.run_coroutine_threadsafe(self.webhook_send(message, sender), self.loop)

def change_presence(self, n):
if n > 0:
activity = discord.Game(name=f"{n} rider{'s'[:n>1]} online")
else:
activity = None
asyncio.run(self.discord_bot.change_presence(activity=activity))
asyncio.run_coroutine_threadsafe(self.discord_bot.change_presence(activity=activity), self.loop)

0 comments on commit 21dcd10

Please sign in to comment.