I'm getting this error after my code runs for a few minutes:
future: <Task finished name='Task-1' coro=<timer() done, defined at c:\Users(my name)\Desktop\DiscordBot\roblox test copy.py:12> exception=KeyError('data')>
I'm pretty new to python so I can't get this to work. Any help would be appreciated.
Here is my code:
from time import sleep
from discord.ext import commands
import datetime
import asyncio
import requests
import json
import time
bot = commands.Bot(command_prefix='!')
async def timer():
await bot.wait_until_ready()
channel = bot.get_channel(my discord channel, not sending in case it can be traced to my server)
msg_sent = False
while True:
r = requests.get('https://badges.roblox.com/v1/users/2642375267/badges?limit=10&sortOrder=Desc')
badgedata = r.json()['data']
risetimes = []
for d in badgedata:
badgeid = d['id']
risetimes.append(badgeid)
firstThing = risetimes[0]
times = []
for rt in risetimes:
eztime = (str(rt))
times.append(eztime)
xd = requests.get('https://badges.roblox.com/v1/users/2642375267/badges/awarded-dates?badgeIds=' + str(firstThing))
badgegaineddata = xd.json()['data']
badgegainedtime = []
for ig in badgegaineddata:
badgegaineduwu = ig['awardedDate']
badgegainedtime.append(badgegaineduwu)
firstElement = badgegainedtime[0]
date_string = str(firstElement)
Thedatetime = date_string
date_string = date_string[:26]
date_format = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f")
unix_time = datetime.datetime.timestamp(date_format)
unix_time = unix_time - 18000
dt = datetime.datetime.fromtimestamp(unix_time)
currentunixtime = time.time()
if unix_time > currentunixtime -3:
await channel.send("https://www.roblox.com/badges/" + str(firstThing))
await channel.send(dt)
msg_sent = True
sleep(3)
await asyncio.sleep(1)
bot.loop.create_task(timer())
bot.run('token')
Related
I'm new to programming and I'm trying to implement function to my Telegram bot, which should check data from database, compare time and send notification if time has come.
However I have this type of mistake:
DeprecationWarning: There is no current event loop loop =
asyncio.get_event_loop()
Here is a function code:
async def run_notify():
while True:
base = sq.connect("actions.db")
cur = base.cursor()
all_data = cur.execute("SELECT * FROM actions").fetchall()
delta = timedelta(days=1)
for each_train in all_data:
each_train = str(each_train)
each_train = re.sub("[(|)|'|,]", "", each_train)
data_info = datetime.strptime(each_train, "%d %m %Y %H:%M")
today = datetime.now()
if today == (data_info - delta):
await bot.send_message(chat_id=-530468333, text= f"Reminder {data_info}")
await asyncio.sleep(1)
And the main part:
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.create_task(run_notify())
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
How can I fix this Error and are there any other possible ways to implement Notifications?
Thanks
I need to "sleep" the giveaway without the asyncio.sleep , because if the bot goes off it wont continue where it left (i know i need to store the other data as well , however time is needed for this one)
here is the code again :
import aiosqlite
import time
import datetime
import discord
from discord.ext import commands
import asyncio
import os
import random
class Start(commands.Cog):
def __init__(self, client):
self.client = client
def convert(self, timer):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = timer[-1]
if unit not in pos:
return -1
try:
val = int(timer[:-1])
except:
return -2
return val * time_dict[unit]
#commands.command()
async def start(self, ctx, duration, winners: str, *, prize):
timer = (self.convert(duration))
winners = int(winners.replace("w",""))
await ctx.message.delete()
timestamp = time.time() + timer
epoch_time = int((time.time() + timer))
embed = discord.Embed(title = f"{prize}", description = f'React with 🎉 to enter\nEnds: <t:{epoch_time}:R> (<t:{epoch_time}>)\nHosted by {ctx.author.mention}\n', color =
ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
embed.set_footer(text=f'Winners : {winners} | Ends at \u200b')
gaw_msg = await ctx.send(content = "<:spadess:939938117736091678> **GIVEAWAY** <:spadess:939938117736091678>",embed=embed)
await gaw_msg.add_reaction("🎉")
db = await aiosqlite.connect("main.db")
cursor = await db.cursor()
await cursor.execute(f'SELECT * FROM storingStuff WHERE msgID = {gaw_msg.id}')
data = await cursor.fetchone()
if data is None:
await cursor.execute(f'INSERT INTO storingStuff (msgID, guildID) VALUES({gaw_msg.guild.id} , {gaw_msg.id})')
await db.commit()
await asyncio.sleep(timer)
new_msg = await ctx.channel.fetch_message(gaw_msg.id)
users_mention = []
for i in range(winners):
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
winner = random.choice(users)
users_mention.append(winner.mention)
users.remove(winner)
displayed_winners = ",".join(users_mention)
endembed = discord.Embed(title=f"{prize}", description=f"Winner: {displayed_winners}\nHosted by: {ctx.author.mention}", color = ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
endembed.set_footer(text= 'Ended at \u200b')
await gaw_msg.edit(content = "<:done:939940228746072096> **GIVEAWAY ENDED** <:done:939940228746072096>",embed=endembed)
await ctx.send(f"Congragulations {displayed_winners}! You won the **{prize}**.\n{gaw_msg.jump_url}")
def setup(client):
client.add_cog(Start(client))
Any help is appreciated
I have a code to receive data from binance, about current prices:
import asyncio
from binance import AsyncClient, BinanceSocketManager
import time
from datetime import datetime
def analyze(res):
kline = res['k']
if kline['x']: #candle is compleated
print('{} start_sleeping {} {}'.format(
datetime.now(),
kline['s'],
datetime.fromtimestamp(kline['t'] / 1000),
))
time.sleep(5)
print('{} finish_sleeping {}'.format(datetime.now(), kline['s']))
async def open_binance_stream(symbol):
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
ts = bm.kline_socket(symbol)
async with ts as tscm:
while True:
res = await tscm.recv()
analyze(res)
await client.close_connection()
async def main():
t1 = asyncio.create_task(open_binance_stream('ETHBTC'))
t2 = asyncio.create_task(open_binance_stream('XRPBTC'))
await asyncio.gather(*[t1, t2])
if __name__ == "__main__":
asyncio.run(main())
How to make analyze function to be called concurently.
Binance sends info in the same time with both streams data (ETHBTC and XRPBTC)
But function analyze will be called only once previous analyze (sleep) is completed.
I wish function analyze is called immediately and independently.
Have you tried to put analyze in a thread. I think it will achieve what you want.
import asyncio
from binance import AsyncClient, BinanceSocketManager
import time
from datetime import datetime
from threading import Thread
def analyze(res):
kline = res['k']
if kline['x']: #candle is compleated
print('{} start_sleeping {} {}'.format(
datetime.now(),
kline['s'],
datetime.fromtimestamp(kline['t'] / 1000),
))
time.sleep(5)
print('{} finish_sleeping {}'.format(datetime.now(), kline['s']))
async def open_binance_stream(symbol):
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
ts = bm.kline_socket(symbol)
async with ts as tscm:
while True:
res = await tscm.recv()
Thread(target= analyze, args = (res)).start()
await client.close_connection()
async def main():
t1 = asyncio.create_task(open_binance_stream('ETHBTC'))
t2 = asyncio.create_task(open_binance_stream('XRPBTC'))
await asyncio.gather(*[t1, t2])
if __name__ == "__main__":
asyncio.run(main())
This should work as expected.
I need to change the format to compare the time to bot send the message, i think it's just change the format strptime() to strftime() or vice-versa, but i dkn how do this, and i want to send this message with the discord bot, but i think it's wrong because if i test just the code of discord bot the (WHILE TRUE:) stop
import discord
from datetime import datetime, date
import datetime
import requests
from time import sleep
import time
url = 'https://www.bdohelper.me/gamez/schedule/EU'
params = dict()
TOKEN = ""
while True:
resp = requests.get(url=url, params=params)
data = resp.json()
boss = data[0]['boss']
time_spawn = data[0]['spawnat']
channel = data[0]['channel']
time_spawn = time_spawn.split('T')
time_spawn = time_spawn.pop(1)
time_spawn = time_spawn.split('.')
time_spawn = time_spawn.pop(0)
time_spawn = datetime.datetime.strptime(time_spawn, '%H:%M:%S').time()
now = datetime.datetime.utcnow().strftime('%H:%M:%S')
now = datetime.datetime.strptime(now, '%H:%M:%S').time()
until_spawn = datetime.datetime.combine(date.today(), time_spawn) - datetime.datetime.combine(date.today(), now)
print(until_spawn)
time.sleep(1)
for_spawn = datetime.time()
print(for_spawn)
if time_spawn == for_spawn:
def sendMessage(message):
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(MY CHANNEL ID)
await channel.send(message)
print("done")
client.run(TOKEN)
if __name__ == '__main__':
sendMessage(time_spawn)```
OUTPUT:
0:04:21 <------- change
00:05:45
Try this (inserted hyphen between % and H):
time_spawn = datetime.datetime.strptime(time_spawn, '%-H:%M:%S').time()
That generally removes leading zeroes when formatting datetimes.
I want to make a discord bot that texts me every day when online classes begin.
import discord
from discord.ext import commands
from datetime import *
import discord.utils
from discord.utils import get
import pytz
local = datetime.now()
tbilisi = pytz.timezone("Asia/Tbilisi")
datetime_tbilisi = datetime.now(tbilisi)
Monday = "Monday"
dro1_saati = 9
dro1_wuti = 30
async def on_ready():
channel = discord.utils.get(client.guilds[0].channels, name = "general")
await client.change_presence(status = discord.Status.online, activity = discord.Game("with z.help_me | Aleksandre"))
#Monday
if Monday == datetime_tbilisi.strftime("%A") and dro1_saati == datetime_tbilisi.hour and dro1_wuti == datetime_tbilisi.minute:
embed = discord.Embed(title = "Monday", description = ": https://us04web.zoom.us/j/78382716896?pwd=RUxiZExKRHFadSszS01pZWk0WVNKQT09k\n ID:783 8271 6886 \n Pass:1010", colour = discord.Colour.blue())
await channel.send(embed = embed)
when I host it on Heroku, it is not working.