我似乎找不到解決方案,每次我運行機器人并在 alt 帳戶上加入服務器時,我都會收到一個錯誤,我無法修復。這是我當前的代碼。
import discord
from discord.ext import commands
import random
import requests
import json
# import bot token
from apikeys import *
intents = discord.Intents().all()
intents.members = True
client = commands.Bot(intents=intents, command_prefix="!")
@client.event
async def on_ready():
print("the bot is now ready for use")
print("--------------------")
@client.command()
async def hello(ctx):
await ctx.send("Hello, I am PineKone")
@client.command()
async def roll(ctx):
await ctx.send(random.randint(1, 6))
@client.event
async def on_member_join(member):
url = "https://jokeapi-v2.p.rapidapi.com/joke/Any"
querystring = {
"format": "json",
"contains": "C#",
"idRange": "0-150",
"blacklistFlags": "nsfw,racist",
}
headers = {
"X-RapidAPI-Key": JOKEAPI,
"X-RapidAPI-Host": "jokeapi-v2.p.rapidapi.com",
}
response = requests.request(
"GET", url, headers=headers, params=querystring
)
# await member.send("Hello, and welcome to my (kone's) bot testing server!")
channel = client.get_channel(1030862181195055148)
# await channel.send("Hello, and welcome to my bot testing server!"
await channel.send(json.loads(response.text)["joke"])
@client.event
async def on_member_remove(member):
channel = client.get_channel(1030862181195055148)
await channel.send("Sad to see you go...")
client.run(BOTTOKEN)
這是我得到的錯誤:
Traceback (most recent call last):
await coro(*args, **kwargs)
File "e:\Discort Bot\main.py", line 55, in on_member_join
await channel.send(json.loads(response.text)["joke"])
KeyError: 'joke'
我設法讓它部分作業,但我得到的唯一輸出是:
{'error': False, 'category': 'Programming', 'type': 'twopart', 'setup': 'Why do programmers wear glasses?', 'delivery': 'Because they need to C#', 'flags': {'nsfw': False, 'religious': False, 'political': False, 'racist': False, 'sexist': False, 'explicit': False}, 'id': 50, 'safe': True, 'lang': 'en'}
然后你有單部分的笑話,它回傳:
{'error': False, 'category': 'Programming', 'type': 'single', 'joke': "Hey Girl,\nRoses are #ff0000,\nViolets are #0000ff,\nI use hex codes,\nBut I'd use RGB for you.", 'flags': {'nsfw': False, 'religious': False, 'political': False, 'racist': False, 'sexist': False, 'explicit': False}, 'id': 41, 'safe': True, 'lang': 'en'}
任何人都有解決方案,或者遇到同樣的問題并設法解決它?
uj5u.com熱心網友回復:
由于并非所有回應顯然都有'joke'密鑰,但是'setup'and 'delivery',您需要執行類似的操作
resp = json.loads(response.text)
if "joke" in resp:
await channel.send(resp["joke"])
elif "setup" in resp and "delivery" in resp:
await channel.send(resp["setup"])
await channel.send(resp["delivery"])
如果需要,您可以await asyncio.sleep(1)在設定和交付之間添加一個...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516862.html
上一篇:RPi上的Python:Errno2沒有這樣的檔案或目錄:'config.json'但config.json與main.py腳本位于同一檔案夾中
