Discord.py bot 未运行 client.loop 或 on_ready 中的任务

问题描述 投票:0回答:0

我为我正在做的一个小项目制作了一个 python 机器人。基本上它所做的就是读取谷歌表格中的一组特定单元格,绘制一个漂亮的小图表并将其保存为图像,然后将其与他们的不和谐 ID 一起发送给他们的 DM 中的用户。

但是,我遇到了一些问题。机器人在 3 分钟左右后继续离线。没什么大不了的,我想我会每 2 分钟将它的状态更改为列表中有趣的内容。但是,无论我是使用 client.loop 事件还是来自 discord.ext 的任务,循环都不会运行。

它们运行的唯一时间是当 discord bot 抛出错误时(比如当我的 wifi 决定有自己的想法时失去连接),或者当 client.loop 事件关于正在被监视的单元格被满足时。

我已经在互联网上搜索过我做错的蠢事,但看在我的份上却找不到原因。谁能帮我?代码如下,有一些更改,不显示令牌或任何东西。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from discord.ext import tasks
import time
import matplotlib.pyplot as plt
import requests
import json
import discord
import random
import asyncio

# Set up the credentials to access the Google Sheets API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(r"json location", scope)

# Authenticate with Google and open the desired sheet
gc = gspread.authorize(credentials)
sheet = gc.open("Spreadsheet name").worksheet('Sheet6')

# Get the initial value of the cell
cell_value = sheet.acell('B2').value

#init some variables
parties = [(20, -16, "royalblue", "BIU"), (-10, -33, "navy", "DXC"), (-10, 9, "gold", "ALP")]
status = [
    'you make questionable political choices.',
    'you lie on your political compass test.',
    'you destroy your political career.',
    'you spam Neutral/Unsure.',
    'you bank on trickle down economics',
    'you expand the government',
    'you storm the Capitol',
    'you claim you did not have sexual relations with that woman',
    'you take secularism as more of a suggestion',
    'you change the definition of morally ambiguous'
    ]

#define some defs
def political_compass(economics, social):
    #this thing really is superfluous now but I cba to remove it
    return (economics, social)

def plot_result(result, parties=None):
    #plot things in a square graph and such
    x, y = result
    fig, ax = plt.subplots()
    ax.scatter(x, y, color="black")
    if parties:
        for party in parties:
            ax.scatter(party[0], party[1], color=party[2], label=party[3])
    ax.set_title("TITLE")
    ax.set_xlim(-50, 50)
    ax.set_ylim(-50, 50)
    ax.axhline(y=0, color="black")
    ax.axvline(x=0, color="black")
    ax.annotate("Economic Left/Right", (35, 0), (0, -5),
                textcoords="offset points", ha="center", va="top")
    ax.annotate("Progressive/Conservative", (0, 45), (-5, 0),
                textcoords="offset points", ha="right", va="center")
    if parties:
        plt.legend(loc="upper right")
    fig.savefig("political_compass.png")
client = discord.Client()

@tasks.loop(minutes=2)
async def status_change():
    cur_status = random.choice(status)
    print('Current status is: Watching '+cur_status)
    await client.change_presence(status=discord.Status.online, activity=discord. Activity(type=discord.ActivityType.watching, name=cur_status))
    
async def sheet_check():
    global cell_value
    await client.wait_until_ready()
    while not client.is_closed():
        time.sleep(1)
        current_value = sheet.acell('B2').value
        if current_value != cell_value:
            print("Cell value has changed from", cell_value, "to", current_value)
            cell_value = current_value
            # Grabbing info
            discord_id = sheet.acell('C2').value
            eco_val = float(sheet.acell('D2').value)
            soc_val = float(sheet.acell('E2').value)
            print(discord_id)
            print(eco_val)
            print(soc_val)

            # make the graph
            result = political_compass(eco_val, soc_val)
            plot_result(result, parties)

            # Upload the image to imgur
            client_id = "ID I WON'T SHARE"
            image = open("political_compass.png", "rb").read()
            headers = {"Authorization": f"Client-ID {client_id}"}
            response = requests.post("https://api.imgur.com/3/image", headers=headers, data={"image": image, "type": "file"})
            if response.status_code == 200:
                response_json = response.json()
                print(f"Image uploaded successfully: {response_json['data']['link']}")
            else:
                print("Failed to upload image")
            # Send with discord bot
            user = user = await client.fetch_user(discord_id)
            await user.send(f"Here is your Political Compass result: {response_json['data']['link']}")
            await user.send(f"Additional message")
            await user.send(f"other additional message")
            t = time.localtime()
            current_time = time.strftime("%H:%M:%S", t)
            print("Message sent at " + current_time)
            await asyncio.sleep(10)

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')
    await client.change_presence(status=discord.Status.online, activity=discord. Activity(type=discord.ActivityType.watching, name='myself in the mirror.'))
    channel = client.get_channel(CHANNEL ID) 
    await channel.send('Hello, World!')
    print('He has awaken')
    status_change.start()
    client.loop.create_task(sheet_check())
    
client.run('TOKEN THAT SHOULDNT BE HERE BUT IN A ENV FILE I KNOW')

在此先感谢您的帮助。

我尝试通过 client.loop 和 discord.ext 的任务调用

status_change
,但都没有导致
status_change
在启动时运行,然后连续运行。

loops discord.py task python-asyncio coroutine
© www.soinside.com 2019 - 2024. All rights reserved.