I wrote a new bot and the loop seems to be working but for some reason I can’t get any of my commands to work within discord? Any idea what I did wrong?
import discord
from discord.ext import commands, tasks
import sqlite3
from datetime import datetime, timedelta
import pytz
import asyncio
# Discord bot setup
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Database connection
conn = sqlite3.connect('notices.db', check_same_thread=False)
c = conn.cursor()
# Define database schema
c.execute('''CREATE TABLE IF NOT EXISTS notices
(id INTEGER PRIMARY KEY, user_id INTEGER, type TEXT, start_date TEXT, end_date TEXT)''')
conn.commit()
# Function to insert notice into database
def insert_notice(user_id, notice_type, start_date, end_date=None):
c.execute("INSERT INTO notices (user_id, type, start_date, end_date) VALUES (?, ?, ?, ?)",
(user_id, notice_type, start_date, end_date))
conn.commit()
# Function to remove notice from database
def remove_notice(notice_id):
c.execute("DELETE FROM notices WHERE id=?", (notice_id,))
conn.commit()
# Function to get all notices from database
def get_all_notices():
c.execute("SELECT * FROM notices")
return c.fetchall()
# Function to get notices by user from database
def get_notices_by_user(user_id):
c.execute("SELECT * FROM notices WHERE user_id=?", (user_id,))
return c.fetchall()
# Command to handle late notices
@bot.command()
async def late(ctx, date: str):
try:
date_time = datetime.strptime(date, '%Y-%m-%d')
except ValueError:
await ctx.send("Invalid date format. Please use YYYY-MM-DD.")
return
# Store late notice in database
insert_notice(ctx.author.id, 'late', date_time.strftime('%Y-%m-%d'))
await ctx.message.delete()
# Command to handle absence notices
@bot.command()
async def absent(ctx, start_date: str = None, end_date: str = None):
print("Command received:", start_date, end_date) # Debugging statement
if start_date is None or end_date is None:
await ctx.send("Usage: !absent [start_date] [end_date]\nExample: !absent 2024-02-25 2024-02-28")
return
try:
start_date_time = datetime.strptime(start_date, '%Y-%m-%d')
end_date_time = datetime.strptime(end_date, '%Y-%m-%d')
except ValueError:
await ctx.send("Invalid date format. Please use YYYY-MM-DD.")
return
if start_date_time > end_date_time:
await ctx.send("End date must be after start date.")
return
# Store absence notice in database
insert_notice(ctx.author.id, 'absent', start_date_time.strftime('%Y-%m-%d'), end_date_time.strftime('%Y-%m-%d'))
await ctx.message.delete()
# Function to post notices
async def post_notices():
notices = get_all_notices()
if notices:
notice_str = "**Notices:**\n"
for notice in notices:
notice_type = notice[2]
start_date = notice[3]
end_date = notice[4]
if notice_type == 'late':
notice_str += f"<@{notice[1]}> will be late on {start_date}.\n"
elif notice_type == 'absent':
notice_str += f"<@{notice[1]}> will be absent from {start_date} to {end_date}.\n"
channel = bot.get_channel(CHANNEL_ID_HERE) # Replace YOUR_CHANNEL_ID_HERE with your channel ID
await channel.send(notice_str)
# Scheduled task to post notices every day at 6:00 PM EST
@tasks.loop(hours=24)
async def scheduled_post_notices():
await bot.wait_until_ready()
tz = pytz.timezone('US/Eastern')
now = datetime.now(tz)
if now.hour == 18: # 6:00 PM EST
await post_notices()
# Scheduled task to delete previous day's notice every day at 6:00 PM EST
@tasks.loop(hours=24)
async def scheduled_delete_previous_notice():
await bot.wait_until_ready()
tz = pytz.timezone('US/Eastern')
now = datetime.now(tz)
if now.hour == 18: # 6:00 PM EST
notices = get_all_notices()
for notice in notices:
remove_notice(notice[0])
# Start scheduled tasks
@bot.event
async def on_ready():
scheduled_post_notices.start()
scheduled_delete_previous_notice.start()
# Print a message indicating that the bot is running
print("Bot is now running.")
# Run the bot
async def run_bot():
await bot.start("TOKEN_HERE")
# Start the bot within asyncio event loop
if __name__ == "__main__":
asyncio.run(run_bot())