如何为我的Discord机器人实现定时消息?

huangapple go评论145阅读模式
英文:

How can I implement a scheduled message for my discord bot?

问题

以下是您要翻译的内容:

我已经在Python中创建了一个Discord机器人它会发送我每周的大学课程表的屏幕截图目前只有在使用“!”前缀召唤它时才能工作但现在我希望它能在每个星期日下午3点自动执行相同的课程表发送功能

以下是当前与“!”前缀一起工作的代码

[代码部分未翻译]

我已经尝试使用schedule导入实现我的当前代码但机器人不再发送屏幕截图或消息我在Python方面经验有限所以欢迎任何建议

以下是带有schedule导入的当前代码

[代码部分未翻译]

请注意,我只翻译了您的代码部分,不包括您的问题或其他内容。如果您需要进一步的帮助或有其他问题,请随时提出。

英文:

I have created a discord bot in python that sends a screenshot of my weekly university schedule. It currently works if you summon it with the "!" prefix, but now I want it to execute the same schedule sending function by itself every sunday at 3PM.

Here is the current code that works with the "!" prefix

import discord
from discord.ext import commands
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import pyautogui
import datetime
from datetime import date
import schedule

bot = commands.Bot(command_prefix = "!", intents = discord.Intents.all())

BOT_TOKEN = "token"

my_date = datetime.date.today() 
year, week_num, day_of_week = my_date.isocalendar()

@bot.event
async def on_ready():
    print("Bot is alive")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e) 

@bot.command()
async def schema1(ctx, classid="myclassname"):
    #channel = bot.get_channel(CHANNEL_ID)
    driver = webdriver.Chrome()
    driver.get('school.com') 
    driver.set_window_size(1024, 768)
    time.sleep(3)
    pyautogui.moveTo(1000, 440, duration = 1)
    pyautogui.click(1000, 440)                
    pyautogui.typewrite(classid)             
    pyautogui.typewrite(["enter"])
    time.sleep(3)
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") 
    time.sleep(2)
    await ctx.send(f"Schedule week {week_num} for {classid}")
    driver.save_screenshot('screenshot.png')
    await ctx.send(file=discord.File('screenshot.png'))
bot.run(BOT_TOKEN)

I have tried implementing my current code with the "schedule" import, but the bot doesn't send the screenshot nor the message anymore. Im not very experienced in python so any suggestions are welcome.

import discord
from discord.ext import commands
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import pyautogui
import datetime
from datetime import date
import schedule
import sys
import tracemalloc

bot = commands.Bot(command_prefix = "!", intents = discord.Intents.all())

BOT_TOKEN = ""

my_date = datetime.date.today() 
year, week_num, day_of_week = my_date.isocalendar()

@bot.event
async def on_ready():
    print("Bot is alive")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)

async def continuation(ctxx):
    await ctxx.send(f"Schedule week {week_num} for class")
    await ctxx.send(file=discord.File('screenshot.png')) 

def job():
    channel = bot.get_channel()
    driver = webdriver.Chrome()
    driver.get('school.com') 
    driver.set_window_size(1024, 768)
    time.sleep(3)
    pyautogui.moveTo(1000, 440, duration = 1)
    pyautogui.click(1000, 440)                
    pyautogui.typewrite("classname")             
    pyautogui.typewrite(["enter"])
    time.sleep(3)
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") 
    time.sleep(2)
    driver.save_screenshot('screenshot.png')
    continuation(channel)   
    print("Job done")    
    #driver.quit()

schedule.every().sunday.at("15:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

答案1

得分: 0

你可以使用 discord.py 的 tasks 扩展。这个模块允许你轻松创建在特定时间运行的循环。
在创建一个每天下午3点运行的循环之后,你只需要找出何时是星期日。
以下是一个简单的示例,每周日下午3点(UTC)运行一次的循环:

from discord.ext import commands, tasks
import datetime

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

# 创建一个每天下午3点(UTC)运行的循环
@tasks.loop(time=datetime.time(hour=15, minute=0))
async def job_loop():
    weekday = datetime.datetime.utcnow().weekday()
    if weekday == 6:  # 星期日
        # 在这里执行你的任务
        await job()

@bot.event
async def on_ready():
    # 你需要启动循环
    if not job_loop.is_running():
        job_loop.start()

bot.run(TOKEN)
英文:

You can use the tasks extension from discord.py. This module allows you to easily create loops that run at a certain time of day.
After creating a loop that runs every day at 3 PM, you only need to find out when is sunday.
Here's an simple example of a loop that runs every Sunday at 3 PM (UTC):

from discord.ext import commands, tasks
import datetime


bot = commands.Bot(command_prefix = "!", intents = discord.Intents.all())


# creating a loop that runs every day at 3 PM UTC
@tasks.loop(time=datetime.time(hour=15, minute=0))
async def job_loop():
    weekday = datetime.datetime.utcnow().weekday()
    if weekday == 6:    # sunday
        # do your job here
        await job()


@bot.event
async def on_ready():
    # you need to start the loop
    if not job_loop.is_running():
        job_loop.start()


bot.run(TOKEN)

huangapple
  • 本文由 发表于 2023年5月25日 17:29:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定