Reputation: 85
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)
Upvotes: 0
Views: 3559
Reputation: 3424
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.
Upvotes: 1