nori
nori

Reputation: 85

Discord bot gathering info with JSON/Python Displays Same Data

I want to make a Discord bot. Everything works fine until I want to gather some information from a website using JSON and Python.

The data gets collected, but everytime I type my command in Discord in order to get my information, it displays the same data it used, like it's only getting it ONE TIME - when I connect the bot to my server. Which is exactly what it does.

How can I make it so it gathers the data again every time someone types the command?

Example: I have the command !status, and whenever I type it, my bot takes the status of a Game Server from a website using JSON. Let's say the server is online so it displays "Status: Online" but if the server closes and I type !status again, it still says the status is Online. I have to re-connect the bot to the Discord server so it picks the status up.

I get it that my python script only works one time.

Here's a snippet:

r = requests.get('http://etcthewebsite')

json_data = json.loads(r.text)
status_server = json_data['status']
def on_message(message):
    if message.content == "!status":
        yield from client.send_message(message.chanel, "Status is: " + status_server)

Hope you guys understand what I mean. I repeat: the code works fine and whatnot, but it doesn't pick the information every time I type the command; only once - when THE BOT enters the server.

Upvotes: 0

Views: 2699

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 60994

You should be getting the external data from the server every time you serve it to a user. Depending on how often you expect it to change, you could try to keep a copy of it and keep track of how long ago you accessed it, but that's probably unnecessary.

def on_message(message):
    if message.content == '!status':
        r = requests.get('http://etcthewebsite')
        json_data = json.loads(r.text)
        status_server = json_data['status']
        yield from client.send_message(message.chanel, "Status is: " + status_server)

Edit:

As an aside, you can use discord.ext.commands to make writing bot commands a little simpler.

from discord.ext import commands
import requests

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

@bot.command()
async def status():
    r = requests.get('http://etcthewebsite')
    json_data = json.loads(r.text)
    status_server = json_data['status']
    await bot.say('Status is {}'.format(status_server))

Upvotes: 1

Related Questions