How to change format 00:00 to 0:00, datetime - python

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.

Related

BinanceSocketManager doesn't show futures_user_socket()

I'm using Binance UMFutures testnet and want to build stream for user_data ( order updates).
Keys are ok. Other methods like klines work perfect as well. But .futures_user_socket() shows nothing when I place or cancel orders. Could you please advice what am I doing wrong?
`
from binance import AsyncClient , BinanceSocketManager
import asyncio
api_key_testnet = '<--->'
secret_key_testnet = '<--->'
async def user_data_listener(client):
bm = BinanceSocketManager(client)
async with bm.futures_user_socket() as stream:
while True:
res = await stream.recv()
print(res)
async def main():
client = await AsyncClient.create(api_key_testnet,secret_key_testnet,testnet=True)
await user_data_listener(client)
if __name__ == "__main__":
asyncio.run(main())
`

How to set up Notifications using Aiogram

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

Why am I getting this error with Asyncio?

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')

How to loop in Discord.py?

I've tried to make the loop function but the bot ignores commands from the user as well as I searched all over the internet how to fix it but I still haven't got any answers. Here is my code:
from discord.ext import tasks, commands
import discord
import json
import requests
# My function
#tasks.loop(seconds=10)
async def covloop():
while True:
time.sleep(10)
cov = requests.get("https://covid19.th-stat.com/api/open/today")
covdate = json.loads(cov.text)['UpdateDate']
cf = json.loads(cov.text)['NewConfirmed']
with open("data.json", 'r+') as file:
data = json.load(file)
updateTime = data['date']
print(updateTime)
if updateTime == covdate:
pass
elif updateTime != covdate:
await bot.get_channel(827873382263029770).send('New confirmed: {}'.format(cf))
data['date'] = covdate
file.seek(0)
json.dump(data,file)
file.truncate()
print(str(covdate))
bot = commands.Bot(command_prefix=["$"],case_insensitive=True)
#bot.event
async def on_ready():
print("We've logged in as {0.user}".format(bot))
covloop.start()
So it's actually simple, just remove while True.

how to send message at a specific hour in a day in discord?

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.

Categories

Resources