television/src/discordbot/discordbot.py

77 lines
2.2 KiB
Python
Raw Normal View History

2024-01-16 10:42:22 -05:00
import asyncio
2024-01-14 21:45:31 -05:00
import os
2024-01-15 22:32:57 -05:00
import requests
import discord
from discord.ext import commands, tasks
2024-01-16 10:42:22 -05:00
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
2024-01-14 21:45:31 -05:00
# Read env variables
bot_token = os.environ.get('DISCORDBOT_TOKEN', 'token')
scheduler_hostname = os.environ.get('SCHEDULER_API_HOSTNAME', 'tv.example.com')
# Discord API Intents
2024-01-16 11:16:02 -05:00
intents = discord.Intents.all()
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
intents.message_content = True
2024-01-14 21:45:31 -05:00
# Discord client
bot = commands.Bot(command_prefix="!", intents=intents)
2024-01-14 21:45:31 -05:00
# Scheduler
scheduler = AsyncIOScheduler()
2024-01-15 16:48:20 -05:00
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
scheduler.start()
@bot.command(name='hello')
async def hello(ctx):
await ctx.channel.send('Hello!')
@bot.command(name='epg')
async def epg(ctx):
2024-01-15 22:32:57 -05:00
try:
db_url = f'https://{scheduler_hostname}/database'
if requests.get(db_url).status_code == 200:
response = requests.get(db_url)
response.raise_for_status()
2024-01-16 11:42:23 -05:00
content = response.json
await ctx.channel.send('epg:')
if content != {}:
for item in content:
if item['start_at'] == 'now' or item['start_at'] == 'never':
await ctx.channel.send('x')
continue
else:
await ctx.channel.send('x')
await ctx.channel.send(item['start_at'])
else:
await ctx.channel.send('Empty database!')
2024-01-15 22:32:57 -05:00
except Exception as e:
print(e)
@bot.command(name='start_task')
async def start_task(ctx):
# Schedule a task to run every 5 seconds
2024-01-16 11:34:04 -05:00
scheduler.add_job(func=my_task, id='my_task_id')
#scheduler.add_job(func=tick, id='tick_id', args=(ctx))
2024-01-14 22:07:15 -05:00
2024-01-16 11:34:04 -05:00
@tasks.loop(seconds=10)
async def my_task():
# Your asynchronous task goes here
2024-01-16 11:22:34 -05:00
print()
2024-01-16 11:34:04 -05:00
await bot.channel.send('Running my_task')
async def tick():
await bot.channel.send('Tick! The time is: %s' % datetime.now())
2024-01-16 10:42:22 -05:00
# Run the bot with your token
bot.run(bot_token)