#discord-bots
1 messages · Page 799 of 1
File "c:\botok\Clanbot\cogs\cogbirthday.py", line 71, in callback
await interaction.message.edit(content="Your birthday is...", view=View(Day(value, newOptions[0:15]), Day(value, newOptions[-(days-15):])))
File "c:\botok\Clanbot\cogs\cogbirthday.py", line 76, in __init__
self.options = options
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\disnake\ui\select.py", line 180, in options
self._underlying.options = value
AttributeError: 'Day' object has no attribute '_underlying'
```bro now I'm getting harassed by the lib
godamn
I won't even remember what I code xD
lmfao
I remember doing some stuff with django because it kept erroring on migrations
idk what I did but it worked so, I'm not complaining
what are you trying to do?
birthday reminder
ok and where are you storing the dates?
imageine he says txt
So I have this commandpy #@commands.check_any(commands.has_permissions(manage_guild = True), commands.has_permissions(manage_messages = True)) @commands.guild_only() @commands.command(description = f"Lets you toggle a role as mentionable or not. Command will show the current state if no state is given.") async def mentionable(self, ctx, role: discord.Role, mentionable: Optional[bool]): if mentionable is None: await ctx.send(f"{role.mention} is {'pingable' if role.mentionable is True else 'not pingable'}") else: if mentionable is True: await role.edit(reason = f"{ctx.author} made {role.name} pingable.", mentionable = mentionable) else: await role.edit(reason = f"{ctx.author} made {role.name} not pingable.", mentionable = mentionable)which is producing this errorpy ERROR:cogs.error_handler:Forbidden: 403 Forbidden (error code: 50013): Missing Permissions (In mentionable) Traceback: File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/moderation.py", line 179, in mentionable await role.edit(reason = f"{ctx.author} made {role.name} pingable.", mentionable = mentionable) File "/usr/local/lib/python3.8/dist-packages/discord/role.py", line 349, in edit data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload) File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 248, in request raise Forbidden(r, data)when both I and the bot have administrator permissions
is that modmail source
the role is higher than the bots roles or urs
maybe make a new role for testing and try it on that
NameError: name 'guild' is not defined
emb.set_footer(text="© Все права защищены The Greatest", icon_url = guild.icon_url)
Help please
full code?
depends on which modmail your talking about, if your even aiming that at me
error in this code snippet
buddy you need to know some basic python before diving into making discord bots
🐑
how to handle this exception?
discord.ext.commands.errors.MemberNotFound: Member "<@&938899544333254768>" not found.
Ok...🐑
nope that's not it (hope the pics are allowed) also i did try making a new test role and same error
You have to catch it in a command handler
yes try and except, but which exception do i catch?
hm
its not try and except
incorrect
but this one works for no user mention, how do i create on for invalid user mention
except AttributeError:
error_em = discord.Embed(title=f"Error Using That Command", colour=0xFFFFFF)
error_em.add_field(name="Error:", value=f"No User Mention", inline=False)
error_em.set_footer(text="https://github.com/zoaq1")
await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=error_em)```
!d disnake.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
this is the correct tag @kindred epoch
what would go where "exception" is
you use exception to get all the error attributes, meaning, you can use exception.name to get the error name
how do I create a loop so that the code asks a question in the console and takes the answer?
How would I make a bot respond to an event that like sends what the user has said. For example if I type Hello I want the bot to send "You said Hello"
multiple ways
you could use on_message or wait_for()
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
loop to ask a qution in the console? why would you need a loop to ask a question?
What difference does it make to you?
🤷♂️
a loop is very un-needed
What is difference between bot.command and client.command?
its the same thing, just depends how you define your commands.Bot as
Hmmmm
here is mine, mine is client.command because thats what i defined it as client = commands.Bot(command_prefix="t!",help_command=None,intents=intents)
best practice is to define your commands.Bot as bot and not client
im gonna define it as botandnotclient just cause u said that
best practice is to subclass the bot 🗿
🗿 true
lul
so after looking at my bots perms it has the admin toggled on but the manage roles toggled off, I would assume that admin overrides manage roles but should I update my bots OAuth?
you dont need to because it already has the perms it needs to manage roles, no idea why its not working
guess it's like one of my other commands, that ones just not responding at all with zero errors so at least mentionable is responding
whats the command code maybe i can help
How would I write it?
Because the last time I did it the bot malfuctioned and spammed
yo i keep getting the error ModuleNotFoundError: No module named 'discord_components' not too sure why, been trying to fix it (py 3.9.10 in vsc)
you probably forgot some checks to stop the bot from looping a response from itself
bot.command should naturally do that for you aswell but its always good to double check and make sure
#@commands.check_any(commands.has_permissions(manage_guild = True), commands.has_permissions(manage_messages = True))
@commands.guild_only()
@commands.command(description = f"Lets you toggle a role as mentionable or not. Command will show the current state if no state is given.")
async def mentionable(self, ctx, role: discord.Role, mentionable: Optional[bool]):
if mentionable is None:
await ctx.send(f"{role.mention} is {'pingable' if role.mentionable is True else 'not pingable'}")
else:
if mentionable is True:
await role.edit(reason = f"{ctx.author} made {role.name} pingable.", mentionable = mentionable)
else:
await role.edit(reason = f"{ctx.author} made {role.name} not pingable.", mentionable = mentionable)```
which function can be to sent a message
It keeps sending this message
You said <Message id=938924529584074753 channel=<TextChannel id=874847853888036949 name='・general' position=6 nsfw=False news=False category_id=874847853888036947> type=<MessageType.default: 0> author=<Member id=775381954564587560 name='AGT Kizi' discriminator='7078' bot=False nick='AGT KIzi' guild=<Guild id=874847853888036946 name='Test Server' shard_id=0 chunked=False member_count=7>> flags=<MessageFlags value=0>>
i meant the commands which are not responding lul
why is not work ? ```py
@client.event
async def on_ready():
print("send id")
x=input()
user = client.get_user(x)
await user.send('hii')
async def on_message(msg):
if msg.author == bot:
...
else:
await msg.channel.send(f"You said {msg}")```
I feel really dumb
But I can't get it
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
oop, it's this one. it's being registered in my help command at least and I can invoke it in jishaku and it works fine but as soon as I run it it just doesn't respond py @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def badwords(self, ctx, *, words: str): print(f"\nInput: {words}") guild = 448405740797952010 if ctx.guild is None else ctx.guild.id data = await self.bot.get_data(guild) words = [w[1:] if w[0] == " " else w for w in words.split(",")] bad_words = set(words) if data[28] is None else set(data[28] + words) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], guild,) await ctx.send(embed = discord.Embed(colour = ctx.author.colour, title= "Update: Bad Words List:", description = f"`{', '.join(data[28])}`."))
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.message' has no attribute 'edit'
help
Show code
I'll try to help
pastebin cause this will count as spam
v
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
does bad_words print?
number thing on line 10 messed up ignore that
bruh fr is there something im missing
so whats wrong with the code
Wait why are they f strings?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.message' has no attribute 'edit'
used to have stuff inside, not anymore
Shouldn't it be like troll_message.edit
import discord
import os
# Import load_dotenv function from dotenv module.
from dotenv import load_dotenv
# Loads the .env file that resides on the same level as the script.
load_dotenv()
# Grab the API token from the .env file.
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
# Client Bot
#client = discord.Client()
client = discord.Client()
@client.event
async def on_ready(channel_id, title, url, desc, name, thumbnail, test):
channel = client.get_channel(channel_id)
embed=discord.Embed(title=title, url=url, description=desc, color=0xff0000)
embed.set_author(name=name, url=url)
embed.set_thumbnail(url=thumbnail)
embed.add_field(name="test", value=test, inline=False)
await channel.send(embed=embed)
# Run the client on the server
client.run(DISCORD_TOKEN)
What am i doing wrong. I would like to sent an embeded message to a channel
TypeError: 'coroutine' object is not callable
Not message.edit
aint no way
how did i not notice that
okay, it's decided to work today
I'd spent hours troubleshooting it yesterday
lol
client.run(DISCORD_TOKEN) is indented
none of this will work
dont indent client.run
thanks
anyone know how to make an alias to a jishaku command
e.g prefix pull instead of prefix jsk pull
okay so I think I lucked out that first time bc it's not responding anymore, even the prints aren't doing anything
hm
what is wrong with the import and defining client
Nothing is wrong with that
It's just that the code is too old to run
And doing stuff in on_ready is really bad since it can be executed multiple times
What should i use. I would like to call the function in a interation
What do you want to do specifically?
i have another function which iterates over data when there is a match i would like to call discord bot to send embeded message to a specific channel
Ok, do you have the id of that channel?
yes, I already got it working with on_ready but the program is not closing. After sent a message the function have to sent another one again
Again as I said on_ready is not for sending messages.
cant find in documentation what i should use
Ok, I think you don't have the basics of setting up and making a disord bot down, so take a look at this help guide made by one of the helpers here https://vcokltfre.dev
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Ah i see thanks
God no
Please just start learning the docs
Try coding yourself simple commands, each time a little harder
Cant find something? --> docs
Still can't find it? --> here
docs doesn't really explain syntax.
how to get ideas for bot commands
@client.command()
async def test(ctx):
for member in ctx.guild.members:
member = member
print(member)
Anyone know why this is not worken 
is there an event for when someone creates an invite?
!d disnake.on_invite_create
disnake.on_invite_create(invite)```
Called when an [`Invite`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite "disnake.Invite") is created. You must have the [`manage_channels`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_channels "disnake.Permissions.manage_channels") permission to receive this.
New in version 1.3.
Note
There is a rare possibility that the [`Invite.guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.guild "disnake.Invite.guild") and [`Invite.channel`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.channel "disnake.Invite.channel") attributes will be of [`Object`](https://docs.disnake.dev/en/latest/api.html#disnake.Object "disnake.Object") rather than the respective models.
This requires [`Intents.invites`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.invites "disnake.Intents.invites") to be enabled.
Indention?
i use dpy panda
indentation is all good
is it the same?
No its not
!d discord.on_invite_create
discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.
New in version 1.3.
Note
There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.
This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.invites "discord.Intents.invites") to be enabled.
ah alright
Exactly the same
thanks panda
Is there a way to run some code right before the bot stops working? I want to log it when my bot turns off by writing the current time and date to another file. I have the writing part done, but can't find a way to execute code as the bot is being shut off.
nvm on my code the indent is fine
i just got the indent wrong on message
still not workin though 
No errors either
@client.command()
async def test(ctx):
for member in ctx.guild.members:
member = member
print(member)
This does not work 
indention is still inconsistent
Idk i paste it there and the lines shift so i just add the spaces in myself
What code editor are you using to write this in?
But when i run the code and try the command theres no error, there would be an error if it was indento problemo right?
Visual Code
u feel dumb rn py except AttributeError or discord.ext.commands.errors.MemberNotFound(f"@{member}"): error_em = discord.Embed(title=f"Error Using That Command", colour=0xFFFFFF) error_em.add_field(name="Error:", value=f"Invalid/No User Mention", inline=False) error_em.set_footer(text="https://github.com/zoaq1") await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=error_em)
that works
member = member?
Add a print statement at the beginning of the code to see if its even being run
I've been trying to find ways to experiment with user input but can't really think of a way.
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
To work with user inputs in the first place
Hmm
Are there any examples of how this is used
You mean via discord or via the console?
how do i add last fm commands to my bot?
like i wanna make a “nowplaying” command and a “set” command
We don't help with music bots sorry
Via discord
The commands extension supports that
nono it doesn’t play music
it just shows what you’re playing in last fm
fm?
Yes
many bots have it
They're in the docs
what's that
Ok and?
There are tons of murderers, doesn't mean its allowed
The world's largest online music service. Listen online, find out more about your favourite artists, and get music recommendations, only at Last.fm
I hate how the YT tutorials never teach how to navigate through the docs lmao.
💀 you know what i meant
yes
Then you'll have to do that with aiohttp and is outside the scope of this channel
someone sent me a code but i wanna learn how to integrate it
Nvm i found the error 🤣
example up here
🤣 I made a stupid mistake
That code is disturbing to look at
I agree
Completely breaks pep8
No white space, bare exceptions, no spacing, lines that look over 79 characters, etc.
Also variable naming
Terrible variable naming and not using snake_case
damn
@bot.command()
async def test(ctx, *, arg):
await ctx.send(arg)
Btw what is the * for
Probably the wrong way to explain it but it packs all the arguments in to arg
So
!test a b c d
arg will be a b c d
👍
Also is args a variable?
iirc yes
Thanks
why doesnt the gif embed work?
The link isn't a gif
It'd end with .gif
If you clicked on it it'd not take you to the gif
You need to download it. You'd get an MP4 instead of a GIF file.
So you have to then convert the MP4 to a GIF file and then post it.
i got it
Lemme send you a converted gif
Why not use an embed?
? I said it tells you the basics, does he know what he needs to look at in the docs? No.
Spaghetti code: 🤡
No I mean an actual embed
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
but why would i need to embed an already embeded gif
@commands.Cog.listener(name="on_invite_create")
async def log_invites(self, ctx, invite):
await self.bot.wait_until_ready()
if ctx.guild is None:
return
log_channel = self.bot.get_channel(938936724535509012)
log_server = self.bot.get_guild(755722576445046806)
if invite.guild.id == log_server.id:
embed = discord.Embed(title="Invite Created", color=0x00ff00)
embed.add_field(name="Invite Details", value=f"{invite.url}, {invite.created_at}, {invite.expires_at},\n{invite.max_age}, {invite.max_uses}, {invite.temporary},\n{invite.max_uses}, {invite.inviter}, {invite.uses}")
await log_channel.send(embed=embed)
Ignoring exception in on_invite_create
Traceback(most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
TypeError: log_invites() missing 1 required positional argument: 'invite'``` why is this happening?
To make it look better?
It isn't embedded
That isn't the embed we are talking about
they're talking about an actual embed
It's about embed within embed
but why do i need to embed it
Lemme show an example
you dont need to but it looks neater if it is
this is what they're talking about
anyway can i get some help with this
Hmm
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
@spark wigeon
Thanks yo
np
Btw I want to create a minigame where users can give inputs for questions and answers. And all the inputs are compiled somewhere and these are used for quizzes.
anyway to make the command type seporators look better? Im just using a normal field atm
...
i know u think ur cool and all but this is a place to help others not be rude
I'm sorry if it sounded rude. It wasn't my intention.
anyway to separate the sections better? heres what im doing now:
@client.command()
async def help(ctx):
help_em = discord.Embed(title=f"Here are my Commands:", colour=0xFFFFFF)
help_em.add_field(name="Fun Commands" , value="Commands to use when your bored or when you want to prank someone.", inline=False)
help_em.add_field(name="t!troll" , value="Trolls any user mentioned.", inline=True)
help_em.add_field(name="t!avatar" , value="Gets any user's avatar.", inline=True)
help_em.add_field(name="Utility Commands" , value="Useful Utility that has many Useful Features", inline=False)
help_em.add_field(name="t!ping" , value="Displays my ping in MS.", inline=True)
help_em.add_field(name="t!stats" , value="Displays Stats about this Server.", inline=True)
help_em.add_field(name="Other Commands" , value="Misc. Commands, or just uncatergorized Commands.", inline=False)
help_em.add_field(name="t!help" , value="A List of Useful Commands.", inline=True)
help_em.add_field(name="t!invite" , value="Sends a URL You can use to Invite me to a Server.", inline=True)
help_em.add_field(name="t!source" , value="Sends a URL to see my Source Code.", inline=True)
help_em.set_footer(text="https://github.com/zoaq1")
await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=help_em)
Don't hard code a help command
Instead, subclass it
can i send a video link without having the link at the top like this
You'd have to send it as an attachment rather than send the link
but i have like 500 links lmao
@ client.command()
# @has_permissions(administrator=True)
async def RoulleteAt(ctx, user: discord.User):
channel = client.get_channel(hitagi)
blankChannel = discord.utils.get(ctx.guild.text_channels, name=None)
userId = user.id
targetMember = discord.Guild.get_member(user.id)
await ctx.send(targetMember)
in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: get_member() missing 1 required positional argument: 'user_id'
How come this doesn't work? I tried user_id like 15 ways
ctx.send with user.id returns properly
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
¯\_(ツ)_/¯
i guess im fucked
right, I pass an Id to it and it's not returning a member
am I missing something?
Please fix your naming
change
Variables and functions should be in snake_case
targetMember = discord.Guild.get_member(user.id) to target_member = ctx.guild.get_member(user.id)
Using other wise in this context is bad practice
ah, the issue is I can't send the user to the channel can I?
ctx.send won't work on discord.Guild.get_members output
No issue after removing ctx.send
Sorry, React developer lol
you should use the ctx instead of the whole discord.Guild.get_member
we want an admin to use the mention of a user to be able to play a game with that user
I already have the game working from ctx of a user firing it
but we want to @ someone into the game
user.mention??
no, since the user is a param, you can refrence it like that
no
yoiu dont need to use the whole function name like that
test_var = user.mention
Then fix it
chill lol
@ client.command()
# @has_permissions(administrator=True)
async def RoulleteAt(ctx, user: discord.User):
channel = client.get_channel(hitagi)
blank_channel = discord.utils.get(ctx.guild.text_channels, name=None)
target_member = user.mention
# await ctx.send(target_member)
So, all we need now is to be able to move target_member to another channel. And I think I can figure that out pretty easily from the API
thanks all
user is your discord.User object therefore you can use the mention attribute
RoulleteAt to roullete_at
python interpreter doesn't like anything non snake_case?
Always remember, discord.py is heavily object oriented
it doesn't matter, but its pep8 styling
What are the performance differences, because the user is running that command
It's fine with it but it's bad practice
you should follow it
and roullete_at is a lot uglier than RouletteAt
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
Pep8 is the style guide of python
how do i make it where someone makes there status a certain word or sentence it sends a message
Like something that automatically formats your code?
Yes, or at least enforces rules in my editor
in React/React Native I use eslint, with prettier and it won't let me compile until I fix my linter issues
in strict mode that is
I'm not aware of anything like that
it enforces standards like casing, tabing etc
You could try asking in #python-discussion
how do i make it where someone makes there status a certain word or sentence it sends a message
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
yep something similar to eslint would be nice, perhaps also a config file like .eslintrc, but obviously for python, afaik don't know if one exists but would be awesome
ok, I now have target_member properly set, and it properly returns the user.
How can I disconnect this user? Or move them to a blank channel like I was before using ctx?
await ctx.author.move_to(blankChannel)
What's the equivalent to this but for a user mention?
Someone said python black, looks like a good start
on_member_update will only take before & after
I think it's important to have this for new users tbh
it helped me a ton years ago in react
Agreed
But I don't know if it's possible to enforce this in python since it's quite different from Node projects
I just want when they change there bio to something certain and then when they change it back it removes a role
Yes, on_member_update is what you need
async def roulette_at(ctx, user: discord.User):
channel = client.get_channel(hitagi)
blank_channel = discord.utils.get(ctx.guild.text_channels, name=None)
target_member = user.mention
# await target_member.disconnect()
Looking to do something like this comment
if you pass in None it'll kick them from voice
I don't have the ctx to use here, but target_member variable
str' object has no attribute 'move_to'
do I need id?
And how exactly did you get target_member?
async def roulette_at(ctx, user: discord.User):
target_member = user.mention
ID yes, but the actual instance object would be preferable
from Discord.user props
oh just leave out that 2nd line then
typehint to discord.Member
then you can just do, member.move_to(None)
When possible you should always try to pass around objects rather than strings or IDs since it makes things much more easier and efficient to work with
async def roulette_at(ctx, user: discord.Member):
channel = client.get_channel(hitagi)
blank_channel = discord.utils.get(ctx.guild.text_channels, name=None)
await ctx.send(user)
user.move_to(blank_channel)
Don't think that'd work
Did setting var = object convert to a string?
Just pass in None to move_to
also you don't need the channel and blank_channel variables
If done right this can be done in 2 lines
channel is used for channel.send
we use it to send to different channels depending on where we want the spam lol
I have some vars at the top with each channel ID
No, you can do that with ctx.send()
we don't want it sending the message to the channel the command was executed in
🤔 In that case sure
the replies are very large
😆
it's for a dumb game, and it replies with large paragraphs
Ah okay then make sure you do channel.send() rather than ctx.send()
Since right now it looks like you're using ctx.send()
ah, just for testing to make sure I could get the user object
that's all, thank you though
I think I can finish this now
One last thing, just rename your user to member as it's a discord.Member not a discord.User, not important but just consistency and to avoid confusing yourself
how do you guys come up with command ideas
Steal them
Personally I don't, haven't made a bot in, oh, a very long time haha
what bot commands have u made
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
Idk
Anytime
Lol, discord bots are so saturated with the same base level commands and there really hasnt been much diversity outaide of specific bots designed for particular servers like python bot here or some special dnd bots that link to other dnd websites
Exactly what I have been saying
Discord bot space is pretty bland right now
Main reason im learning it is to get more used to apis for web dev lol. Its also a fun little project i can pick and choose what it does for me and my friends private server
I think discord adding views and selects was nice
how do cogs with slash cmd
^ very good project to use as a learning experience
I dont think its much of an issue with what discord allows. Bots pretty much have access to whatever is needed to make them work. Anything for specific features would just have to come from some other sort of python classes and then translated to fit the discord api
My funny random monkey picture command uses the google api to get the result and converts it to a url to embed into the message for discord. 90% of that functions code is working with the google api lol
Setup correctly discord could probably work as a frontend for something like a note based webapp. Its kinda redundant given discord naturally could be used like that...
True, but for many people discord bots are an excellent way to get acquainted with python or learn more about different aspects of programming
Fair enough
If you're making a discord bot not for the purpose of learning, there are plenty of tools that get the job done
It's a win-win regardless of your intentions
do i need to import something for embed
That's odd, it's not even picking up its own message?
That's not a slash command, that's a regular message
I think its "from discord import Embed" if not that one than its discord.ext
should this work
It should work, looks like the f string is missing a " though
Since that's a slash command, I would recommend using ctx.response.send_message
@client.event
async def on_message_delete(message):
logChanID = db(f"logChan-{message.guild.id}")
if logChanID == "None":
return
logChan = client.get_channel(logChanID)
msgCHAN = message.channel.mention
embed = discord.Embed(title=f"Deleted Message",description=f"{message.content}", color=0xFF0000)
embed.add_field(name=f"Channel", value=f"{msgCHAN}")
embed.set_author(name=message.author)
embed.set_footer(text="View audit log for more information.")
await logChan.send(embed=embed)
that is my code
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message_delete
logChanID = db(f"logChan-{message.guild.id}")
TypeError: 'Database' object is not callable
thats my error message
im using replit db
why is the thing not colored, it was before ( the white text)
ctx.send for slash commands doesn't return the original message. Because of which the message var in your case will give None
replit db is a bad idea, consider going with something more robust such as sqlite or postgresql
I'd suggest getting the role separately via utils.get
replit db is easier then the others though
And then passing that object to member.add_roles

If you have the role id why not fetch it?
sqlite is a file-based database, it's just as easy if not easier than replit db
Does the message have any reactions?
also much more reliable and easier to work with (provided you use the right defaults)

w h a t
now what do i do @sick birch
Can you not fetch a role?
getting this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.message' has no attribute 'delete' while using this await message.delete() even tho my import is this from discord import *
it's discord.Message, not discord.message. Using a wildcard import will cause issues like this
Don't use a wildcard import
Pep8 says that's a nono
Please just import discord
Convolutes the namespace, just like what it's doing right now
no way i didnt notice that
too bad
no
;-;
then you won't be able to fix your issue
It's only going to make things difficult for you, like this case
You need to call it on an instance of discord.Message, not the class or the discord.message module
It's literally causing your issue
It's looking for a module in discord named message rather than a variable
It's Embed
Capital E
Aight guys I think they got it
I.e ThisIsAClass
Classes will always use PascalCase
Worth assuming all classes in discord.py are named the same
Yup. Just look at discord.User, discord.Member, commands.Bot
I'm just adding discord and commands to make it more clear
should i do await.embed
cuz rn it only bans, doesnt show embed
Probably because you're not sending the embed
You need to send it
await ctx.send(embed=embed)
More like, predefining the embed is good practice
And I assume they understood they didn't pass it as an argument
Yep
Like
embed1=discord.Embed(title="write title here", description="insert description here")
await ctx.send(embed=embed1)```
I wrote the var as embed1 to make the last line more clear
how do i make it where someone makes there status a certain word or sentence it sends a message
before will be the profile before, after is after. You'd want to check if after contains a certain word or phrase, then send a message
so how would i do that?
You've specified the discord.Member class in the f-string. Not your member argument.
so is it capitaliziation
The difference between lowercase and uppercase, yes
both before and after are discord.Member objects, and you can access their profile with the attributes of discord.Member:
where do i have that
unless im blind
In the embed you've defined
thats discord.Embed
The syntax highlighting matches what you have typehinted for the function
Don't capitalise it
Member is the discord.py class, member is your argument.
You need to use an instance of the object, not the object itself
If it really confuses you to that degree, please don't directly import Member
Would be less confusing if you didn't from discord import Member, and just used discord.Member
@client.event
async def on_message_delete(message):
logChanID = db(f"logChan-{message.guild.id}")
if logChanID == "None":
return
logChan = client.get_channel(logChanID)
msgCHAN = message.channel.mention
embed = discord.Embed(title=f"Deleted Message",description=f"{message.content}", color=0xFF0000)
embed.add_field(name=f"Channel", value=f"{msgCHAN}")
embed.set_author(name=message.author)
embed.set_footer(text="View audit log for more information.")
await logChan.send(embed=embed)
that is my code
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message_delete
logChanID = db(f"logChan-{message.guild.id}")
TypeError: 'Database' object is not callable
thats my error message
im using replit db
when did dpy get the send_friend_request method?
Looks like it's deprecated
😔 f
Is that a better way of doing it? Importing it in the class that its used instead of the top of the document? Or is it just a preferance thing?
Why you even gotta friend a bot in the first place
Its ideal to, hardly makes a different
Would be better if you just did import discord that way you don't convolute the namespace and don't confuse yourself
these errors
how can i learn programming language
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ah fair enough. Ill have to go and adjust my code for that.
Don't have to, if you don't get yourself confused and don't mind the namespace a little bit more filled up it really doesn't make a difference
But if you want to you can easily change it with some nifty Find & Replace
ctrl/cmd + d if your on vsc
Or Ctrl+Shift+H for the entire directory - if you have cogs
@commands.Cog.listener()
async def on_guild_emojis_update(self, guild, before, after):
async for t in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.emoji_delete):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(guild.id)]
channel_id = channel_config[0]
except:
pass
with open(enable_path, "r") as f:
enabled = json.load(f)
if not str(guild.id) in enabled:
return
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(t.user.id) in whitelisted[str(guild.id)]:
return
remove_emoji = [r for r in before if r not in after]
for em2 in remove_emoji:
before_emoji = await em2.read()
try:
if remove_emoji:
await guild.ban(t.user, reason="Anti-Nuke: Deleting Emojis")
try:
emoji_display = await guild.create_custom_emoji(name=em2.name, image=before_emoji)
try:
if str(guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**EMOJI LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{t.user}`\nID: `{t.user.id}`\nPing: {t.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member deleted a emoji!\n\n**__BEFORE__**\n\nEmoji Name: `{em2.name}`\nID: `{em2.id}`\n\n**__AFTER__**\n\nEmoji Name: `{emoji_display.name}`\nID: `{emoji_display.id}`\nEmoji: {emoji_display}\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Emoji has been replaced! (If asset was found!)", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
except:
pass
except:
continue
async for i in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.emoji_create):
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(guild.id)]:
return
add_emoji = [r for r in after if r not in before]
for em1 in add_emoji:
if add_emoji:
await guild.ban(i.user, reason="Anti-Nuke: Creating Emojis")
await em1.delete()
Ill play around and see what i prefer. I need to round out my file structure so maybe it will be small enough it doesnt make enough of a difference. On that note. Whats the best folder structure for a bot? One folder with files for each command or folders for each command?
why is this code blocking?
i mean not continuing
if a emoji is created to delete the emoji
this again :I
Usually people have one file per cog, and related commands are grouped inside each cogs. Allows for dynamic cog reload/unload
it happens when the channel is not foung in the guild id
- Do you have a problem? 2. I found why this is happening
JSON causes all sorts of annoying issues like this, I really do suggest you use something more robust like a database
Robin i will keep using json for now.. thanks tho
do you know how can i pass the code if the channel is not found in the guild.id?
that would be great
if channel not in guildID:
pass
I havent quite got into cogs yet but i think this will make sense in time. Would cogs be relateble to like a folder and the "cog" just tells the bot you can use whats in this container?
Though with what little discord.js experience I have, they suggest creating one file for each command, if you want to do that I suppose you could as well, not sure how well you could do this dynamically since JS has import/export
Sure, you can think of them as a folder of commands
Registering one cog would register all the commands within, and it allows you to hot-reload your bot (have code changes take effect without turning off and on the bot)
You fetch the channel in this block, correct? And that is when the channel is not found?
try:
channel_config = config_channel[str(guild.id)]
channel_id = channel_config[0]
except:
pass```
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(guild.id)]
channel_id = channel_config[0]
except:
pass
if str(channel_id) not in config_channel[str(guild.id)]:
pass
the channel is not found because the channel is not added
reason why im trying to pass that
basically it shouldn't send the logs
@sick birch
You should probably get a NoneType if there is no channel under that guild
So you can check for that accordingly and pass the case
Ill try set this up later when im home. Do you mind helping me if i get stuck with it later? Ive pulled up the pinned resources to help with stuff but if im working outside of those i may need some help
it wont send the error because
the 2nd part won't run
cuz the channel is not found in the first code
so will it be status or activity
line 72 is blockage
it won't continue if the channel is not found in the 1st code like i said
so i gotta pass that
somehow
anyone know how to fix that?
Sure! Feel free to ask :)
robin what should i use? 
if the channel is found
it works
i can't fucking understand this shit anymore
How are you currently trying to grab the channel because that line would be wher the issue actually is
so imma tell what's going again
if the channel is not found the code won't continue (it will not delete the emoji when is created) and is going to be stuck in that loop.. that's why i'm trying to pass it if the channel is not found basically pass the channel and not send the logs
for em2 in remove_emoji:
before_emoji = await em2.read()
try:
if remove_emoji:
await guild.ban(t.user, reason="Anti-Nuke: Deleting Emojis")
try:
emoji_display = await guild.create_custom_emoji(name=em2.name, image=before_emoji)
try:
if str(channel_id) not in config_channel[str(guild.id)]:
if str(guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**EMOJI LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{t.user}`\nID: `{t.user.id}`\nPing: {t.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member deleted a emoji!\n\n**__BEFORE__**\n\nEmoji Name: `{em2.name}`\nID: `{em2.id}`\n\n**__AFTER__**\n\nEmoji Name: `{emoji_display.name}`\nID: `{emoji_display.id}`\nEmoji: {emoji_display}\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Emoji has been replaced! (If asset was found!)", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
pass
except:
pass
except:
pass
except:
continue
should i try this? even tho doesn't make ah lot of sense
What's with all the bare excepts lol
i gotta try multiple things
maybe the emoji asset fails so i gotta except that
another try is to get the log channel
It's just suppressing every single exception though
Sure. But that's not good design
it looks bad on discord tbh
i will try to see if that pass actually does smth
brb
ofc not
hey does anyone have a vanityroles bot? like say a user puts my vanity link in their status the bot auto gives them a role
for em2 in remove_emoji:
before_emoji = await em2.read()
try:
if remove_emoji:
await guild.ban(t.user, reason="Anti-Nuke: Deleting Emojis")
try:
emoji_display = await guild.create_custom_emoji(name=em2.name, image=before_emoji)
try:
if str(channel_id) in config_channel[str(guild.id)] and str(guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**EMOJI LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{t.user}`\nID: `{t.user.id}`\nPing: {t.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member deleted a emoji!\n\n**__BEFORE__**\n\nEmoji Name: `{em2.name}`\nID: `{em2.id}`\n\n**__AFTER__**\n\nEmoji Name: `{emoji_display.name}`\nID: `{emoji_display.id}`\nEmoji: {emoji_display}\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Emoji has been replaced! (If asset was found!)", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
except:
pass
except:
continue
makes more sense checking both things
is a wrong check
awesome
You can code it up pretty easily, on_member_update
i dont know how to 😦
@client.event
async def on_message_delete(message):
logChanID = db(f"logChan-{message.guild.id}")
if logChanID == "None":
return
logChan = client.get_channel(logChanID)
msgCHAN = message.channel.mention
embed = discord.Embed(title=f"Deleted Message",description=f"{message.content}", color=0xFF0000)
embed.add_field(name=f"Channel", value=f"{msgCHAN}")
embed.set_author(name=message.author)
embed.set_footer(text="View audit log for more information.")
await logChan.send(embed=embed)
that is my code
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message_delete
logChanID = db(f"logChan-{message.guild.id}")
TypeError: 'Database' object is not callable
thats my error message
im using replit db
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
hold up
CRAP
i forgot to remove my vanity
@client.event
async def on_member_update(before, after):
if str(before.status) == "":
if str(after.status) == "":
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
there
for em2 in remove_emoji:
before_emoji = await em2.read()
try:
if remove_emoji:
await guild.ban(t.user, reason="Anti-Nuke: Deleting Emojis")
emoji_display = await guild.create_custom_emoji(name=em2.name, image=before_emoji)
if str(guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**EMOJI LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{t.user}`\nID: `{t.user.id}`\nPing: {t.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member deleted a emoji!\n\n**__BEFORE__**\n\nEmoji Name: `{em2.name}`\nID: `{em2.id}`\n\n**__AFTER__**\n\nEmoji Name: `{emoji_display.name}`\nID: `{emoji_display.id}`\nEmoji: {emoji_display}\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Emoji has been replaced! (If asset was found!)", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
continue
Don't worry yourself with what it was before
as long as it has the vanity after you should be good
It doesn't matter what the user's status was before
Also make sure remove the role once the user removes the vanity from their status, it's the same thing except in reverse
@client.event
async def on_member_update(before, after):
if str(after.status) == "":
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
oh
and maybe instead of == you can use in for greater flexibility: that way,
this status would give them the role:
join discord.gg/somelink!
@sick birch how can i check if the guild id or channel is not in the json
n to continue otherwise
@client.event
async def on_member_update(before, after):
if str(after.status) in "":
if str(before.status) in "":
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
like this?
Like I mentioned before if channelID not in guildID: continue
oof
crap
@commands.Cog.listener()
async def on_guild_emojis_update(self, guild, before, after):
async for t in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.emoji_delete):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(guild.id)]
channel_id = channel_config[0]
except:
pass
if str(channel_id) not in config_channel[str(guild.id)]:
continue
like this?
Use SQLite instead of json
if vanity in after status:
# give role
if vanity not in after status:
# take away role
wut
@client.event
async def on_message_delete(message):
logChanID = db(f"logChan-{message.guild.id}")
if logChanID == "None":
return
logChan = client.get_channel(logChanID)
msgCHAN = message.channel.mention
embed = discord.Embed(title=f"Deleted Message",description=f"{message.content}", color=0xFF0000)
embed.add_field(name=f"Channel", value=f"{msgCHAN}")
embed.set_author(name=message.author)
embed.set_footer(text="View audit log for more information.")
await logChan.send(embed=embed)
that is my code
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message_delete
logChanID = db(f"logChan-{message.guild.id}")
TypeError: 'Database' object is not callable
thats my error message
im using replit db
im kinda new to coding so like could u try to dumb down even more pls
That's psuedocode, I can't really simplify that any further
robin is still not working
Not sure, it's stumped me at this point as well
oof could u tell me where i put the code at?
Inside the on_member_update event
If you are new, a discord bot is not a good project
And yes discord.py is not necessarily a beginner library, you should have a pretty decent understanding of the language before proceeding as it will make things much easier for you to work with
You're calling the database
I'm assuming you're not supposed to do that
You need a strong understanding of OOP and async programming
well what else am i supposed to do-?
You access and set values using [], not ()
oh your right, ty
1 step closer @sick birch
if str(guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**EMOJI LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{t.user}`\nID: `{t.user.id}`\nPing: {t.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member deleted a emoji!\n\n**__BEFORE__**\n\nEmoji Name: `{em2.name}`\nID: `{em2.id}`\n\n**__AFTER__**\n\nEmoji Name: `{emoji_display.name}`\nID: `{emoji_display.id}`\nEmoji: {emoji_display}\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Emoji has been replaced! (If asset was found!)", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
else:
continue
the continue does it's job here
but if the logs are off like no guild id
it won't work
Ignoring exception in on_message_delete Traceback (most recent call last): File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event await coro(*args, **kwargs) File "main.py", line 69, in on_message_delete await logChan.send(embed=embed) AttributeError: 'NoneType' object has no attribute 'send'
I get that error now...
logChan is None
Fix your variable names. They should be in snake_case
how would changing the name fix it?
just follows pep8
fine
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
you don’t wanna build bad practices
i dont think they are bad practices... its faster to type it in camelCase
how? i define it though
But that’s not how Python is typed
that is JavaScript, c#, etc
well c# is mostly PascalCase I think
then why do my python teachers tell me to type in camelCase? 🤔
js too
lmao what the fuck
They don't know what they're talking about
I’m sorry but those teachers don’t know what they are doing
It is bad practice
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
but still, how is logChan None? I define it
but then why did my school hire them as coding teachers? 🤔
School doesn't know what they're doing
idk I’m not the school
that is true lmao, they make alot of mistakes
https://mystb.in/MyrtleBaseballScholar.python - i kinda fixed it but if the channel is not found in the guild id is going to return.. block the 2nd part of the code, How can i continue the code if the channel is none?
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Taken directly from the pep8 documentation
anyways, how is logChan None?
Is the id correct?
yes
Are you using get or fetch?
niether
Can you send the code?
@client.event
async def on_message_delete(message):
logChanID = db[f"logChan-{message.guild.id}"]
if logChanID == "None":
return
print(logChanID)
logChan = client.get_channel(logChanID)
msgCHAN = message.channel.mention
embed = discord.Embed(title=f"Deleted Message",description=f"{message.content}", color=0xFF0000)
embed.add_field(name=f"Channel", value=f"{msgCHAN}")
embed.set_author(name=message.author)
embed.set_footer(text="View audit log for more information.")
await logChan.send(embed=embed)
yes
?
no
Damn
why?
Disnake has getch
So get gets the channel from the cache
If its not in the cache it returns None
Therefore if its None you need to fetch it
wait so should i do
logChan = discord.utils.get(server.channels, name=logChanID)
instead?
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Make a check with an if statement. If get returns None use fetch
logChan = client.get_channel(logChanID)
if logChan == None:
logChan = await fetch_channel(logChanID)
?
yeah ik
Ignoring exception in on_message_delete
Traceback (most recent call last):
File "/home/runner/Database-testing/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 64, in on_message_delete
logChan = await fetch_channel(logChanID)
NameError: name 'fetch_channel' is not defined
RoboDanny (official discord.py bot) has a nice little function in the source code inside the commands.Bot subclass that's like:
class Bot(commands.Bot):
...
async def get_or_fetch(...):
# get, then return
# if that doesn't work, then fetch & return
pretty useful function to have ^
oh wait that’s smart
Indeed, thought it was pretty cool when I was taking a peek inside
Thats what getch does
is there a way i can delete the dropdown after its been interacted with once?
Timeout
!d discord.Interaction.delete_original_message
await delete_original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
did you see the error message?
no , i dont want to delete it after a given time
i want to delete it as soon as it has been interacted with
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
It would be self.bot.fetch_channel in a cog
i dont use cogs
guild.fetch_channel() normally
i honestly dont care... for me, its easier to use camelCase and not use cogs
bot.fetch_channel also works but using guild.fetch_channel is faster
Makes it easy now but help command is going to be hell
Well, it's making an API request either way
well im making my own help command
iirc bot.fetch_channel goes through all the channels the bot can see while guild.fetch_channel goes through the channels in the guilds
Less channels to go through with guild.fetch_channel
That's get_channel, fetch_* all make API requests
I know it still makes an api request
You mean server-side?
Yes
Hard coding it?
nope
Well still should just be O(1) since it's just doing a lookup, but obviously discord's backend is quite complex and difficult for non employees to measure
So I think for most purposes bot.fetch_channel may be just a very tiny amount slower, basically negligible
Just to note I'm going off what other people say
I haven't tested this myself
I know its going to make a very little difference I just want them to be informed
So how are you going to make different categories?
can you explain more on what you mean ?
If you don't use cogs you cannot create different categories
discord channel categories?
what do you mean by catagories?
In a help command you create different categories i.e Fun, Utility, Economy
ah thats what you mean
If you're not doing it in cogs you don't have a way to do that automatically
@client.command()
async def help(ctx):
author = ctx.author
async def fButtonReply(interaction):
if interaction.user != ctx.author:
await interaction.user.send("Hey! You can't do that!")
return
await message.edit(embed=fEmbed)
async def iButtonReply(interaction):
if interaction.user != ctx.author:
await interaction.user.send("Hey! You can't do that!")
return
await message.edit(embed=iEmbed)
async def eButtonReply(interaction):
if interaction.user != ctx.author:
await interaction.user.send("Hey! You can't do that!")
return
await message.edit(embed=Eembed)
async def mButtonReply(interaction):
if interaction.user != ctx.author:
await interaction.user.send("Hey! You can't do that!")
return
await message.edit(embed=Membed)
async def uButtonReply(interaction):
if interaction.user != ctx.author:
await interaction.user.send("Hey! You can't do that!")
return
await message.edit(embed=uEmbed)
eButton.callback = eButtonReply
fButton.callback = fButtonReply
iButton.callback = iButtonReply
uButton.callback = uButtonReply
mButton.callback = mButtonReply
view = View()
view.add_item(eButton)
view.add_item(fButton)
view.add_item(iButton)
view.add_item(uButton)
view.add_item(mButton)
message = await ctx.send(embed=Membed, view=view)
Eembed=discord.Embed(title="Emojis", description="Uploads a bunch of selected emojis.")
Eembed.add_field(name="Football Fusion", value=f"`{PREFIX}emoji ff` uploads ff emojis", inline=True)
Eembed.add_field(name="NFL", value=f"`{PREFIX}emoji nfl` uploads nfl emojis", inline=True)
Eembed.set_footer(text=f"Requested By: {author}")
iEmbed=discord.Embed(title="Emojis", description="Uploads a bunch of selected emojis.")
iEmbed.add_field(name="Invite", value=f"`{PREFIX}invite`", inline=True)
iEmbed.add_field(name="Ping", value=f"`{PREFIX}ping`", inline=True)
iEmbed.add_field(name="Server Info", value=f"`{PREFIX}serverinfo`", inline=True)
iEmbed.add_field(name="Member Count", value=f"`{PREFIX}membercount`", inline=True)
iEmbed.add_field(name="Invite", value=f"`{PREFIX}cinvite` creates a invite.")
iEmbed.set_footer(text=f"Requested By: {author}")
fEmbed=discord.Embed(title="Formating", description="Formating Text")
fEmbed.add_field(name="Bolding", value=f"`{PREFIX}bold <text>` bolds the text", inline=True)
fEmbed.add_field(name="italic", value=f"`{PREFIX}italic <text>` italics the text", inline=True)
fEmbed.set_footer(text=f"Requested By: {author}")
uEmbed=discord.Embed(title="Utilitie", description="Utilitie Commands")
iEmbed.add_field(name="Purge", value=f"`{PREFIX}purge <# of messages>` deletes the specified amount of messages.", inline=True)
uEmbed.add_field(name="dm", value=f"`{PREFIX}dm <@ user> <message>` dms the specified user with the specified message.", inline=True)
uEmbed.add_field(name="allowDM", value=f"`{PREFIX}allowDM [enable/disable]` enables or disables the ability for people to dm you using the bot.", inline=True)
Membed=discord.Embed(title="Help", description="Click the corosponding button.")
Membed.add_field(name="Emojis", value="`😀 emojis`", inline=True)
Membed.add_field(name="Formating", value="`💽 format`", inline=True)
Membed.add_field(name="Info", value="`📜 info`", inline=True)
Membed.add_field(name="Utilitie", value=f"`🔧 Utilitie`", inline=True)
Membed.add_field(name="Menu", value="`❌ Menu`", inline=True)
Membed.set_footer(text=f"Requested By: {author}")
eButton = Button(label=':grinning: emojis', style=discord.ButtonStyle.green)
fButton = Button(label=':minidisc: format')
iButton = Button(label=':scroll: info', style=discord.ButtonStyle.primary)
mButton = Button(label=':x: Menu', style=discord.ButtonStyle.red)
uButton = Button(label=':wrench: Utilitie')
wtf
i did that with one of them
Yeah this is very bad
You're hard coding it
thats how i do all of them
Every time you make a command you have to add it
yes
It's a very bad idea
^
All I have to do is spend a couple of hours subclassing my help command(Only have to do it once) and then it's going to work no matter how many cogs/commands I add
see, you have to spend hours
!d discord.ext.commands.MinimalHelpCommand
class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)```
An implementation of a help command with minimal output.
This inherits from [`HelpCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HelpCommand "discord.ext.commands.HelpCommand").
while i dont
i can add a new catargory in 3 minutes
its not that hard
so?
Ask anyone. It's a terrible idea
Also subclassing help command makes it dynamic
nice
@client.event
async def on_member_update(before, after):
if "discord.gg/" in str(after.status):
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
what am i doing wrong !!
Is there anyway to stream a tab on a discord bot?
status is not their custom status thing, it means, idle, online or offline
oof
The name of the activity.
use this
No, bots do not have video streaming capabilities
no, but if you mean youtube together, its possible
@client.event
async def on_member_update(before, after):
if "discord.gg/" in str(after.discord.Activity.name):
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
like, just youtube
like where you can watch videos in vc
I thought I recalled someone showing me a bot like that
i dont mean like youtube, youtube together is a discord feature..
ok
thats not how it works , after.activity.name
would be the thing
https://pypi.org/project/discord-together/ if you wanna try it
@client.event
async def on_member_update(before, after):
if "discord.gg/" in str(after.Activity.name):
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
notice that the a in activity is lower cased :0
oh
this is what I was talking about thx!
okay now how do i make it take the role if it isnt in their status
how do i delete a dropdown message after it has been interacted with?
do i delete them like normal messages or
I was making a afk command in which the afk syatus is set as a variable : ctx.author.mention
AFK = []
But sometimes it didnt take the @ like 4974972397493 is user id and @ivory jackal this is mention sometimes it store it as <8794749724434>
Help..
library?
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
master branch?
v2.0
ah you can do interaction.message.delete()
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
@client.event
async def on_member_update(before, after):
if ".gg/" in str(after.activity.name):
guild = client.get_guild(932840827212931123)
role = discord.utils.find(lambda r: r.name == 'promoter', guild.roles)
await after.add_roles(role)```
how do i make it take the role when i remove my vanity
check pins
i personally prefer epikhost and sneakyhub as a free host
for paid ones you may check pins
add else statement which removes the role....
There aren't that many good free hosting, it's alright for smaller bots but you should decide on an industry standard hosts such as AWS or Google cloud hosting for when you might need to migrate in the future
where do i add it?
Or you can buy yourself a raspberry pi, bit of an initial investment but might pay off in the log run, you can also do other stuff with it
Over time a raspberry pi would most likely end up costing more money than renting a cheap vps
i want the bot to keep checking for a value of variable, there is a thing called @tasks.loop in disnake , is there smth like that in dpy?
do you have the guild object?
You would need to do maintenance, pay electricity bills, wifi bills etc
How'd you get the guild ID?
Cost of scale is also there
Definitely doesn't scale
yes!
what is it called?
it's the same
the same way you would in disnake
its actually a part of discord.py's ext
well
thanks
disnake is a fork of discord.py, so many things are the same
ooh really? nice to know
why did they create a fork tho , what is the difference
disnake has everything discord.py 2.0 had
disnake is supposed to improve on discord.py
so everyone should use disnake?
discord.py is no longer maintained (i.e. wont receive an update)
Not necessarily
There are other discord.py forks, and other libraries that are built from the ground up

which one do u recommend using?
so there are forks
disnake, nextcord, pycord, enhanced-dpy are some popular ones
oh
I recommend base discord.py as I don't like any of the forks much, but it's personal preference
interesting
But don't take my word for it
Try the different ones and find out which you like best
ill suggest disnake in general, but if you want to try something different hikari is a good choice too
i have tried both dpy and disnake , they both have awesome communities
Discord.py is already semi out-dated now with the new features added at least. I wouldn't say the codebase is quite tidy either
Nah i've looked at the code base, kind of weird in some place
agree with you on that one
but i haven't worked on discord bots in a little bit so there's that
What are you talking about, the dpy community is so toxic lol
We all have had different experiences with those communities, if they've had an awesome experience, well, that's awesome!
Still hung up on O(n) get_channel, never gonna leave my thoughts
to much tbh
Of course, the library is not a beginner's library
they expect no beginners
this tbh
theyll always be someone that doesnt know
exactly, thats the point
they wont teach python basics in the server meant for a library support
You should have a pretty decent understanding of python before you attempt discord.py, which is reflected on the community
Only makes things harder for you in the long run
all fetch_* message need to be awaited
all get_* message do not need to be awaited as they only do a cache lookup
You're on the right track, just you have them flipped
they mean, you dont await get_s
and you need to await fetch_s
because its Messageable.fetch_message
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
its not a Guild method
not to be annoying or anything but just curious if anyone knows this lol
did you install the library?
also just wanna mention the fact that i HAVE downloaded it using pip install discord-components and uninstalled it and still have the same issue, ive also checked and its in the lib
yeah, and its worked before but once just broked
also, its not recommended to use 3rd party libraries for components, just use the master branch or some fork
do you have multiple python versions installed?
nope
try pip install discord-components and see if it says requirement already satisfied
im gonna be honest i dont really know python too much lol, i kinda just looked up "discord.py buttons" and that came up
all are already satisfied
Hey there , i am trying to make a bot that does custom link preview for YouTube music links, it will post a link to that song on YouTube as well as Spotify , how do I go about it ,web scrapping or is there a better way to do it ?
well that may get outdated as soon as discord.py stops functioning :)
strongly recommended to use a fork or master branch
you wont need to change your old code either ( expect for the discord_components code)
forks give you slash commands too....
anyways, did you try restarting your ide??
yup lol
what ide are you using ?
visual studio
i also tested it on pycharm and didnt work
check the python configuration settings in it
is it same as the python interpreter you installed the library in
im gonna sound extremely stupid but where do i find that
i dont know either, because im a visual studio code user
try looking for something named configurations
also , try pip show discord-components in the ide's terminal
Name: discord-components
Version: 2.1.2
Summary: An unofficial library for discord components.
Home-page: https://github.com/kiki7000/discord.py-components
Author: kiki7000
Author-email: devkiki7000@gmail.com
License: MIT License
Location: c:\python39\lib\site-packages
Requires: aiohttp, discord.py
Required-by:
PS C:\Users\Blake\Desktop\d.py bot>
An unofficial third-party library of discord.py for discord components. - GitHub - kiki7000/discord.py-components: An unofficial third-party library of discord.py for discord components.
mhm it means that its installed
oh youre using visual studio code right?
or visual studio? they are different
yeah im using vsc
ah, did you use the play button on the right to run the code?
yup
dont do it, install vsc's python extension and use this instead
still get the error
same error?
yup
the exact error is File "c:\Users\Blake\Desktop\d.py bot\main.py", line 4, in <module> from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType ModuleNotFoundError: No module named 'discord_components'
do you have something like this at the bottom?
hmm try using the web installation instead of installing it from ms store
how would i get rid of the ms store version?
it allows you to uninstall it..
oh lmao
now im getting ModuleNotFoundError: No module named 'discord'
did you install the web version?
i did lol
yup
since you uninstalled the previous installation, you would have to install things again

help means a lot
