0

I am curious on how to loop this certain part of my code every 10 seconds.

And how would I make it so instead the Discord API private messages you the price on !price execution rather then normally messages it in the channel?

import requests
import discord
import asyncio

url = 'https://cryptohub.online/api/market/ticker/PLSR/'
response = requests.get(url)
data = response.json()['BTC_PLSR']

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print("PULSAR 4 LIFE")
    print('------')

    price = print('Price:', data['last'])
    pulsar = float(data['last'])
    pulsarx = "{:.9f}".format(pulsar)

    await client.change_presence(game=discord.Game(name="PLSR Price: " + pulsarx))


@client.event
async def on_message(message):
    if message.content.startswith('!price'):
        url = 'https://cryptohub.online/api/market/ticker/PLSR/'
        response = requests.get(url)
        data = response.json()['BTC_PLSR']
        price = print('PLSR Price:', data['last'])
        pulsar = float(data['last'])
        pulsarx = "{:.9f}".format(pulsar)
        await client.send_message(message.channel, 'Price of PULSAR: ' + pulsarx)
4
  • What part are you trying to loop? Commented Feb 14, 2018 at 8:00
  • I want to loop where it requests information from the API URL. So basically the information updates every set amount of time. Commented Feb 14, 2018 at 8:01
  • Basically spamming the user's dms every 10 seconds? o.o Commented Feb 14, 2018 at 8:02
  • Ooooh no. It displays it in the top-right under 'Playing' status. It won't spam anyone, I just want it so when they type in !price it DMs them the price rather then in public chat. I want it to loop repeatedly so that it keeps updating the price accurately. Commented Feb 14, 2018 at 8:02

1 Answer 1

1

First of all, you shouldn't be using the requests module because it isn't asynchronous. Meaning, once you send a request, your bot will hang until the request is done. Instead, use aiohttp. As for the dming user, just change the destination. As for the loop, a while loop will do.

import aiohttp
import discord
import asyncio

client = discord.Client()
url = 'https://cryptohub.online/api/market/ticker/PLSR/'

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print("PULSAR 4 LIFE")
    print('------')

    async with aiohttp.ClientSession() as session:
        while True:
            async with session.get(url) as response:
                data = await response.json()
                data = data['BTC_PLSR']
                print('Price:', data['last'])
                pulsar = float(data['last'])
                pulsarx = "{:.9f}".format(pulsar)
                await client.change_presence(game=discord.Game(name="PLSR Price: " + pulsarx))
                await asyncio.sleep(10) #Waits for 10 seconds


@client.event
async def on_message(message):
    if message.content.startswith("!price"):
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                data = await response.json()
                data = data['BTC_PLSR']
                pulsar = float(data['last'])
                pulsarx = "{:.9f}".format(pulsar)
                await client.send_message(message.author, 'Price of PULSAR: ' + pulsarx)

Also, might I recommend you to check out discord.ext.commands. Its a much cleaner way of handling commands.

Sign up to request clarification or add additional context in comments.

3 Comments

Dude thank you so much your a life-saver. I know I should as a programmer know how to do this on my own, but it's because of personal health related issues that I can't come to learn, but rather have to continuously re-teach myself things, which can end up in finding lack of answers. Thanks!
This site wouldn't exist if everyone knew how to do everything by themselves @BlakeXavier
<3 Much love going to you, have a great rest of your day/night!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.