Discord python bot problem with giveng role - python

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.

Related

how i add a img that a user sent in a discord.py embed

I'm making a suggestion discord bot, and I'd like to know if there's how I can add an image that the user posted on embed
something like
embed.set_image(url=image_url)
the image_url would be the image the user added to the message.
suggestion_channel_id = 925568558241550393
color = 0x3498db
#bot.event
async def on_message(message):
suggestionData = '{}'.format(message.content).replace('?sugestão','')
if message.author == client.user:
return
if message.content.startswith('?sugestão'):
embed=discord.Embed(title ='Nova sugestão!')
embed.add_field(name='Vote Abaixo!', value=suggestionData, inline=True)
channel=bot.get_channel(suggestion_channel_id)
embed.color=color
embed.set_footer(text='Sugestão por ' + message.author.name, icon_url=message.author.avatar_url)
up_emoji = '\N{THUMBS UP SIGN}'
down_emoji = '\N{THUMBS DOWN SIGN}'
msg = await channel.send(embed=embed)
await msg.add_reaction(up_emoji)
await msg.add_reaction(down_emoji)
await message.channel.send('Sua sugestão foi enviada!' + '** ' + message.author.name + ' 😎' + ' **')
token = config("token")
bot.run(token)
You can use message.attachments to get a list of message attachments:
#bot.command()
async def send_image(ctx):
embed = discord.Embed(title="Your attached image")
if len(message.attachments):
embed.set_image(url=ctx.message.attachments[0].url)
await ctx.send(embed=embed)

Update an embed message that already exists in Discord

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)

How to make a set logging channel command

Im trying to make a public bot, and i would want this ticket system witha logging channel it already has a logging channel but how can i modify this to make a command that sets the logging channel?
# --- Ticket Open ---
#client.command()
#commands.guild_only()
async def ticket(ctx):
if ctx.channel.type != discord.ChannelType.private:
channels = [str(channel) for channel in client.get_all_channels()]
if f'ticket-{ctx.author.id}' in channels:
await ctx.message.delete()
else:
ticket_channel = await ctx.guild.create_text_channel(f'ticket-{ctx.author.id}')
await ticket_channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ticket_channel.set_permissions(ctx.author, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
embed = discord.Embed(color=10181046, description=f'Please enter the reason for this ticket, type `-close` if you want to close this ticket.')
embed.set_thumbnail(url='')
await ticket_channel.send(f'{ctx.author.mention}', embed=embed)
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Created",
description="",
color=discord.Colour.green())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
#--- Ticket Close ---
#client.command()
#commands.guild_only()
async def close(ctx):
print(f'{ctx.author} | {ctx.author.id} -> {client.command_prefix}close')
if ctx.channel.type != discord.ChannelType.private:
admin_roles = [834126146215477348,835608325273157733,838859643224326144,835582821221138472,835914273402126376]
if ctx.channel.name == f'ticket-{ctx.author.id}':
await ctx.channel.delete()
elif admin_roles and 'ticket' in ctx.channel.name or ctx.author.id in administrator_ids and 'ticket' in ctx.channel.name:
await ctx.channel.delete()
else:
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Closed",
description="",
color=discord.Colour.red())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
Tip: if you want to create a public bot don't use handwritten channel id, you'd better save to file for all servers in json file and set it with command.
For example this:
{
"server identifier": "system channel identifier",
...
}
I don't know what's wrong with the code.

Message listener not working properly discord.py bot

I'm making a bot, and the message listener I'm using is not picking up other people's messages:
#bot.event
async def on_message(message):
chnl = message.channel.name
ts = time.time()
athr = message.author.display_name
st = datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
with open("logs/chat.txt", "a") as text_file:
#print(f"<{message.created_at} | {athr}> {message}", file=text_file)
print(f"_(#{chnl}) <{st} | {athr}> {message.content}", file=text_file)
return athr, st, message.content
await bot.process_commands(message)
It seems like a simple issue, but I don't see what's wrong.
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
bot = commands.Bot(command_prefix=';')

On_member_join and on_member_leave not working discord.py

I've got on_member_joion and on_member_leave code, and it's not working, this is my code:
intents = discord.Intents.default()
intents.members = True
botprefix = ","
bot = commands.Bot(command_prefix = botprefix, case_insensitive=True, intents = intents)
#bot.event
async def on_mmember_join(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f"Witaj {member.mention} na serwerze **Pogaduszki!**")
#bot.event
async def on_member_leave(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f"Żegnamy {member.mention}, mamy nadzieję że do nas wrócisz")
And this code is not working, there are no errors, can anyone help please??
PS: I'm using https://replit.com
You have an error with your join event.
It should be on_member_join and not on_mmember_join.
Also, you should consider not using on_member_leave but on_member_remove.
Your full code:
#bot.event
async def on_member_join(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f "Witaj {member.mention} na serwerze **Pogaduszki!**")
#bot.event
async def on_member_remove(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f "Żegnamy {member.mention}, mamy nadzieję że do nas wrócisz")
Also have a look at the docs for more:
on_member_remove()

Categories

Resources