television/src/discordbot/discordbot.py

86 lines
2.3 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
2024-01-16 11:50:59 -05:00
counter = 0
@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:45:24 -05:00
content = response.json()
2024-01-16 11:42:23 -05:00
await ctx.channel.send('epg:')
2024-01-16 11:44:04 -05:00
await ctx.channel.send(type(content))
await ctx.channel.send(f'`{content}`')
2024-01-16 11:42:23 -05:00
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)
2024-01-16 11:56:20 -05:00
@bot.command(name='time')
2024-01-16 11:50:59 -05:00
async def time():
await bot.channel.send('The time is: `%s`' % datetime.now())
@bot.command(name='start')
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:50:59 -05:00
@bot.command(name='show')
async def show_task(ctx):
global counter
ctx.channel.send(str(counter))
2024-01-16 11:34:04 -05:00
@tasks.loop(seconds=10)
async def my_task():
2024-01-16 11:50:59 -05:00
global counter
counter += 1
2024-01-16 10:42:22 -05:00
# Run the bot with your token
bot.run(bot_token)