I can't seem to find a solution, every time I run the bot, and join the server on an alt account I get an error, that I can't fix. Here's my current code.
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)
And Here's the error that I'm getting:
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'
I managed to make it work partially, but the only output I'm getting is this:
{'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'}
And then you have single part jokes, which returned:
{'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'}
Anyone got a solution, or faced the same problem and managed to fix it?
CodePudding user response:
Since not all responses evidently have the 'joke'
key, but 'setup'
and 'delivery'
, you'll need to do something like
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"])
If you want, you could add an await asyncio.sleep(1)
between the setup and delivery...