所以我使用discord.py做了一个python不和谐机器人,它工作得很好,直到我尝试使用斜杠命令打开代码版本。我的日志中根本没有错误... 这是我的代码: main.py
import discord
from discord.ext import commands
from datetime import date, timedelta
from icalendar import Calendar
from keep_alive import keep_alive
from config import TOKEN, CHANNEL_ID
keep_alive()
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='$', intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
await client.process_commands(message)
@client.command()
async def date(ctx):
todaydate = date.today()
d1 = todaydate.strftime("%d/%m/%Y")
await ctx.send('Nous sommes le ' + str(d1))
@client.command()
async def cours(ctx, *args):
if not args:
await ctx.send(
"Veuillez spécifier 'today' ou 'demain' après la commande $cours.")
return
if args[0].lower() == 'today':
await display_courses(ctx, date.today())
elif args[0].lower() == 'demain':
await display_courses(ctx, date.today() + timedelta(days=1))
else:
await ctx.send(
"Argument non reconnu. Utilisez 'today' ou 'demain' après la commande $cours."
)
async def display_courses(ctx, target_date):
courses = []
horaires = []
locations = []
e = open('Agenda/groupeD.ics', 'rb')
ecal = Calendar.from_ical(e.read()) #Récupérer le calendar pepal
todaydate = date.today()
d2 = todaydate.strftime("%Y%m%d") #Formatage de la date
# Ajout : définir la variable datejour
datejour = todaydate.strftime("%d/%m/%Y")
for event in ecal.walk('VEVENT'):
Aevent = event.get("DTSTART")
step = Aevent.dt
d3 = step.strftime("%Y%m%d") #Récupération et formatage date cible
horaire = step.strftime("%Hh%M")
location = event.get("LOCATION")
if d3 == d2:
courses.append(event.get("SUMMARY")) #Ajouter
horaires.append(horaire)
locations.append(location)
e.close()
embedVar = discord.Embed(title=f"Emploi du temps {datejour}",
description="Aujourd'hui vous avez : ",
color=0x3853B4)
if len(courses) > 0:
embedVar.add_field(name=courses[0],
value=f"{horaires[0]} en **{locations[0].lower()}**",
inline=False)
if len(courses) > 1:
embedVar.add_field(name=courses[1],
value=f"{horaires[1]} en **{locations[1].lower()}**",
inline=False)
else:
embedVar.add_field(name="Pas de cours",
value="Aucun cours pour aujourd'hui.",
inline=False)
await ctx.send(embed=embedVar)
@client.command()
async def ping(ctx):
# ... (your existing code for $ping)
pass
# Easter egg
@client.event
async def on_message(message):
if message.content.startswith('42'):
embedVar = discord.Embed(
title="42",
description=
"La solution à la grande question sur la vie, l'univers , et le reste, assurément...",
color=0x3853B4)
await message.channel.send(embed=embedVar)
client.run(TOKEN)
该机器人在 Repl.it 上运行,并由 UptimeRobot 维护,顺便说一句,提前谢谢您!
切换模块,放在本地而不是repl.it...
我发现您仍在使用 CTX 来执行斜杠命令。
@client.command()
async def date(ctx):
todaydate = date.today()
d1 = todaydate.strftime("%d/%m/%Y")
await ctx.send('Nous sommes le ' + str(d1))
但是,对于斜杠命令,您需要discord.Interaction,否则它不会显示为斜杠命令。它不会给你一个错误,因为你的代码没有任何问题,只是导入了几个模块但从未使用过(通常用黄色下划线)
这是该代码块的更新代码,请记住对所有其他代码块也执行此操作。
@client.command(name="date", description="WHATEVER_YOUR_DESCRIPTION_IS")
async def date(interation: discord.Interaction):
todaydate = datetime.utcnow() # Using UTC time is more reliable
d1 = todaydate.strftime("%d/%m/%Y")
await interaction.response.send_message('Nous sommes le ' + str(d1))
这些是您需要执行此操作的唯一导入:
import discord
from discord.ext import commands
from datetime import datetime
希望这有帮助!如果是这样,请将此答案标记为已接受:)