K
K
kelly1232021-07-24 13:55:16
Python
kelly123, 2021-07-24 13:55:16

Why is the api not working in my discord.py bot code?

Here is my bot code

import discord
import requests
import json
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.command()
async def ping(ctx):
    await ctx.send('pong')
    
@bot.command()
async def vimeworld(ctx):
    r = requests.get('https://api.vimeworld.ru/online')
    title = r[0]['total'].json
    await ctx.send(title)

bot.run('token')

if I inserted my token at the end, the !vimeworld command just doesn’t work for some
reason

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-24
@kelly123

Does not work - displays an error in the console? Or silently does not work?
If silent, wrap the body of vimeworld() in a block

try:
    ...
except Exception as err:
    print(err)

You can also arrange debug print() to understand where the error occurs / the program freezes.
In general, I see at least an error in the line
r[0]['total'].json
Judging by the JSON that the specified URL gives me, it should look something like this:
json_data = r.json()
total = json_data['total']
await ctx.send(total)

Once you've figured this out, keep the following in mind: discord.py is an asynchronous, single-threaded library. As long as synchronous code is running, like your command handler, the bot can't do anything else. And request is just a synchronous library! While it executes the request, it blocks the program from running. Therefore, if the target site "thinks", your bot will freeze. Migrate the code to a library like aiohttp. It is also asynchronous, and while communicating with the site, your bot will be able to do other things.
And finally, you should not start learning python by writing bots. There are enough pitfalls here. Start with the basics, then come back to this project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question