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.
Related
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())
`
So here's my code, some part are messy because im so angry, error message in the end:
from discord.ext import commands
import discord
import random
from keep_alive import keep_alive
import json
import os
import asyncio
#Game variables and list:
bot = commands.Bot(command_prefix='.')
#Game code here:
def o_acc(ctx):
users = await gbd()
if str(ctx.author.id) in users:
return False
else:
users[str(ctx.author.id)] = {}
users[str(ctx.author.id)]["Wallet"] = 10000
with open("user.json", 'w') as f:
json.dump(users, f)
return True
def gbd():
users = json.load(open("user.json", 'r'))
return users
#Check balance command
#bot.command(name='bal')
async def balance(ctx):
await o_acc(ctx.author)
users = await gbd()
em = discord.Embed(title = f"{ctx.message.author.name}'s balance'")
em.add_field(name = 'Wallet balance', value = users[str(ctx.message.author.id)]['wallet'])
await ctx.send(embed = em)
#These commands should be keep in the end!!!!
bot.run('token(bot showing')
Error message:File "main.py", line 32, in balance await o_acc(ctx.author) File "main.py", line 15, in o_acc if str(ctx.author.id) in users: AttributeError: 'Member' object has no attribute 'author'
Just pass in ctx instead of ctx.author as the argument for o_acc().
#Check balance command
#bot.command(name='bal')
async def balance(ctx):
await o_acc(ctx)
users = await gbd()
em = discord.Embed(title = f"{ctx.message.author.name}'s balance'")
em.add_field(name = 'Wallet balance', value = users[str(ctx.message.author.id)]['wallet'])
await ctx.send(embed = em)
I made a moderator bot but when i launch the code python writes "Process finished with exit code 0". Please check my if something wrong.
import discord
import config # Config is a another py file
client = discord.Client()
#client.event
async def on_message(message):
id = client.get_guild(config.ID)
badwords = ["testword", "testword2"]
unwarnusers = (config.unwarnusers)
for word in badwords:
if word in message.content.lower():
if str(message.author) not in unwarnusers:
warnFile = open("E:/vp2/warns.txt", "a")
warnFile.write(str(message.author.mention) + "\n")
warnFile.close()
warnFile = open("E:/vp2/warns.txt", "r")
warnedUsers = []
for line in warnFile:
warnedUsers.append(line.strip())
warnFile.close()
warns = 0
for user in warnedUsers:
if str(message.author.mention) == user:
warns += 1
if warns > 4:
mutedRole = discord.utils.get(message.guild.roles, name = "JB-MUTED")
await message.author.add_roles(mutedRole)
channel = client.get_channel(959128819137146900)
await channel.send(f"\nUser {message.author.mention} made something bad. \nHe writes:\n{message.content}\nThis happened in {message.channel}\n Warns: {warns}")
Add client.run('token') to the bottom of your code.
I want to update an embed message that my bot has already written in a specific channel, how can I do that? If i try to use message.edit it givesthis error: discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
import discord
import json
from discord.ext import commands
def write_json(data,filename="handle.json"):
with open (filename, "w") as f:
json.dump(data,f,indent=4)
class Handle(commands.Cog):
def __init__(self, client):
self.client=client
#commands.Cog.listener()
async def on_ready(self):
print("Modulo_Handle: ON")
#commands.command()
async def Handlers(self,ctx):
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await ctx.channel.send(embed=embed)
file.close()
#commands.Cog.listener()
async def on_message(self, message):
if str(message.channel) == "solaris™-handle":
author = message.author
content = message.content
user = str(author)
with open ("handle.json") as file:
data = json.load(file)
temp = data['fields']
y={"name":user[:-5],"value":content}
temp.append(y)
write_json(data)
updated_embed = discord.Embed.from_dict(data)
await message.edit(embed=updated_embed)
file.close()
def setup(client):
client.add_cog(Handle(client))
msg_id = 875774528062640149
channel = self.client.get_channel(875764672639422555)
msg = await channel.fetch_message(msg_id)
with open('handle.json','r') as file:
data = json.load(file)
embed = discord.Embed.from_dict(data)
await msg.edit(embed=embed)
Fixed adding this code below write_json(data) and remove
updated_embed = discord.Embed.from_dict(data) await message.edit(embed=updated_embed)
I wanted to know how do make the bot say something in a channel if the "helloworld" command hasn't been used in 1 minute
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('connected')
# Command
#client.command()
async def helloworld(ctx):
await ctx.send('Hello World!')
client.run(TOKEN)```
You could use discord.ext.tasks. I'm not sure if it will work as a command (since commands require invocation), but, given a channel ID, you can send the message to a specified channel repeatedly over some interval of time.
from discord.ext import commands
from discord.ext import tasks
client = commands.Bot(command_prefix='!')
#client.event
async def on_ready():
print('connected')
#tasks.loop(seconds=5.0)
async def helloworld(channel_id=1234567890):
channel = await client.fetch_channel(channel_id)
await channel.send("Hello World!")
client.run(TOKEN)
The time interval argument passed to the tasks.loop() decorator can be seconds=, minutes=, or hours=.
discord.ext.tasks API Reference
You can use a task like Jacob Lee specified and add an extra element to check if hello world has been used.
import json
from datetime import datetime
#client.event
async def on_command_completion(ctx):
if ctx.command.name == 'helloworld':
with open('invoke.json', 'r') as f:
data = json.load(f)
data['time'] = datetime.now().strftime('%y-%m-%d-%H-%M-%S')
with open('invoke.json', 'w') as f:
json.dump(data, f, indent=4)
#tasks.loop(seconds=10)
async def check_hello():
with open('invoke.json', 'r') as f:
data = json.load(f)
if 'time' in data.keys():
if (datetime.now() - datetime.strptime(data['time'], '%y-%m-%d-%H-%M-%S')).total_seconds() > 60:
if 'last_invoked' in data.keys():
if datetime.strptime(data['last_invoked'], '%y-%m-%d-%H-%M-%S') > datetime.strptime(data['time'], '%y-%m-%d-%H-%M-%S'):
return
channel = await client.fetch_channel(channel_id)
await channel.send("Hello has not been used in a minute")
data['last_invoked'] = datetime.now().strftime('%y-%m-%d-%H-%M-%S')
with open('invoke.json', 'w') as f:
json.dump(data)
References:-
on_command_completion