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)
Related
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)
def get_channel_id(client, message):
with open('./json/welcome.json', 'r') as f:
channel_id = json.load(f)
return channel_id[str(message.guild.id)]
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0x767429, description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f" {member.avatar_url} ")
embed.set_author(name=f" {member.name} ", icon_url=f" {member.avatar_url} ")
embed.set_footer(text=f"{ member.guild }", icon_url=f" {member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
channel = client.get_channel(id=get_channel_id)
await channel.send(embed=embed)
#client.command()
async def welcomechannel(ctx, channel_id):
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel_id
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to {channel_id}')
I'd like to have the get_channel_idfunction be the ID of the channel = client.get_channel(id=get_channel_id) but everytime I run it i get the error AttributeError: 'NoneType' object has no attribute 'send'. Can someone please help me
You can simplify the code quite a bit. As mentioned in my comment, you also need to open the JSON when a new user enters the server.
Your own function above is completely redundant and not needed.
I also once changed your welcomechannel command a bit because you don't get far with channel_id, you can use channel: discord.TextChannel instead and it comes out the same.
Here is the command for now:
#client.command()
async def welcomechannel(ctx, channel: discord.TextChannel): # We use discord.TextChannel
with open('./json/welcome.json', 'r') as f:
id = json.load(f)
id[str(ctx.guild.id)] = channel.id # Saving JUST the ID, you also had <#ID> in it
with open('./json/welcome.json', 'w') as f:
json.dump(id, f, indent=4)
await ctx.send(f'Welcome channel changed to `{channel}`')
And now to check the channel. For that we open the JSON in the same way as we did with the command:
#client.event
async def on_member_join(member):
with open('./json/welcome.json', 'r') as f:
wchannel = json.load(f) # Define our channel
try:
if wchannel: # If a channel is set for the server
wchannelsend = member.guild.get_channel(wchannel[str(member.guild.id)]) # Get the channel from the JSON
embed = discord.Embed(color=0x767429,
description=f"Welcome to my server! You are the {len(list(member.guild.members))}th member ")
embed.set_thumbnail(url=f"{member.avatar_url} ")
embed.set_author(name=f"{member.name} ", icon_url=f"{member.avatar_url} ")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url} ")
embed.timestamp = datetime.datetime.utcnow()
await wchannelsend.send(embed=embed) # Send the embed to the channel
else:
return # If no channel was set, nothing will happen
except:
return
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
I have got an error: TypeError: on_message() missing 1 required positional argument: 'member'
How do I fix this error and what do I have to do with it?
Here is my code:
import discord
import config
client = discord.Client()
#client.event
async def on_message(message, member):
id = client.get_guild(config.ID) # ID в файле config
channels = [
647074685535649802,
636901028478058497,
690272147050070158,
694196995887202375,
690276595578962177,
654662320735387648,
650381379892412426,
641704849196711976,
]
badwords = ["лузер", "расизм", "нацизм"]
valid_users = ["Resadesker#1103"]
unwarnusers = ["ResadeskerBOT#7104"]
if str(message.author) in valid_users:
for channelo in channels:
if message.content[:message.content.find(' ')] == "$spam":
channel = client.get_channel(channelo)
await channel.send(message.content[message.content.find(' '):])
for word in badwords:
if word in message.content.lower():
if str(message.author) != "ResadeskerBOT#7104":
warnFile = open("D:/python/disbot/warns.txt", "a")
warnFile.write(str(message.author) + "\n")
warnFile.close()
mutedRole = discord.utils.get(message.guild.roles, name='JB-MUTED')
await member.add_roles(mutedRole)
channel = client.get_channel(696315924591935488)
await channel.send(f"--------------------\nЗа человеком {message.author.mention} было замечено нарушение. \nВот его сообщение: \n{message.content} \nНарушение было в канале {message.channel}\n--------------------")
client.run(config.TOKEN)
You are using old code from before the discord.py rewrite but running a newer version.
Just change your:
#client.event
async def on_message(message, member):
to
#client.event
async def on_message(message):
And it should work.
I have been trying to help a friend fix his discord bot, but I'm stumped on the solution.
from discord.ext import commands
import bs4
import requests
import time
import lxml
adminkey = "CheeseIsTheBest"
keys = open('keys.txt', 'w')
TOKEN = "token goes here"
client = commands.Bot(command_prefix = "!")
client.remove_command('help')
#client.event
async def on_ready():
print("Locked And Loaded Mr. DarkKnight")
#client.command(name='ping')
async def ping(ctx):
await ctx.send('pong')
#client.command()
async def addkey(ctx, key):
if str(ctx.author) == "ironkey#6969" or str(ctx.author) == "ZERO#2020":
with open('keys.txt', 'r+') as file :
file.write(str(key + "\n"))
file.close()
await ctx.send('key added')
else:
await ctx.send('your not authorized to preform this action ' + str(ctx.author))
#client.command()
async def redeemkey(ctx, key):
with open('keys.txt', 'r+') as file:
for line in file:
if str(key.strip()) == str(line.strip()):
with open('keys.txt', 'w') as file:
keyfile = keyfile.replace(str(key), key + " X")
file.write(keyfile)
file.close()
await ctx.send('key redeemed!')
else:
await ctx.send('This key has already been used')
#client.command()
async def unbind(ctx, *, member):
role = discord.utils.get(ctx.guild.roles, name='authenticated')
await client.remove_roles(member, role)
#client.command(aliases=['inv'])
async def invite(ctx):
await ctx.send('https://discordapp.com/api/oauth2/authorize?client_id=645664026160005129&permissions=8&scope=bot')
#client.command()
async def help(ctx):
embed = discord.Embed(color=discord.Color.dark_blue())
embed.set_author(name="Cheese Auth Help Menu", icon_url="")
embed.add_field(name=".ping", value="a simple fun command! usage : .ping")
embed.add_field(name=".invite", value="also used with the command inv, this command will get you an invite link so you can add this bot to your server! usage: .invite")
await ctx.send(embed=embed)
client.run(TOKEN)
Every time I try to redeem the key I added, I get this error:
Ignoring exception in command redeemkey:
Traceback (most recent call last):
File "C:\Users\seang\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79,
in wrapped ret = await coro(*args, **kwargs)
File "C:\Users\seang\Downloads\Bot_for_DarkKnight1-_Copy.py", line 41,
in redeemkey keyfile = keyfile.replace(str(key + X))
UnboundLocalError: local variable 'keyfile' referenced before assignment.
From your code i noticed that keyfile.replace is the problem. Variable keyfile is not assigned or declared (defined) yet.You are reading a file line by line in variable line so I think your code should be
keyfile = line.replace(str(key), key + " X")
The error comes from this line:
keyfile = keyfile.replace(str(key), key + " X")
You're trying to make a new value called 'keyfile', but it relies on information which comes from 'keyfile', which doesn't exist yet.