#discord-bots
1 messages · Page 462 of 1
nice attempt at hiding the id but we still see it
ok tell me id
ok stop shitposting
Lmfao
yes go to #python-discussion instead
nvm
😐
lol
broooooooooooo
but anyways i dont see why you want to do that
@jaunty sparrow tell plz
just store the member id
no one can do anything with that id
and then use Guild.get_member
so its ok to show it
and then Member.mention
oh
so i
then use format
need to put member mention
!d str.format
str.format(*args, **kwargs)```
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces `{}`. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
```py
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
``` See [Format String Syntax](https://docs.python.org/3.10/library/string.html#formatstrings) for a description of the various formatting options that can be specified in format strings.
and pass in member=your_member
guys
how can i get unix timestamp from a datetime object?
i have this code but it dont want to send the welcome msg in the channel
@bot.event
async def on_message_join(member):
channel = bot.get_channel(885907606558871642)
embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!")
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
ah
not message
i'm really dumb
tysm
like i'm trying to do a simple welcome message
!d time.time this is also there hehe
time.time() → float```
Return the time in seconds since the [epoch](https://docs.python.org/3.10/library/time.html#epoch) as a floating point number. The specific date of the epoch and the handling of [leap seconds](https://en.wikipedia.org/wiki/Leap_second) is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as [Unix time](https://en.wikipedia.org/wiki/Unix_time). To find out what the epoch is on a given platform, look at `gmtime(0)`.
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
and like it dont send the message in the channel
!e
import time
print(time.time())
Don't ping random people
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
1631288065.1466405
Yups
the bot have enough perms?
yeah
like send_message and embed_links
he have administrator perms
<t:1631288065:R>
Remove the point
😭
mhm
@hasty iron thx bro formats work
yea ?
does it show any error?
nah
@bot.command(pass_context=True)
async def meme(ctx):
embed = discord.Embed(title="", description="")
async with aiohttp.BotSession() as cs:
async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
I dont get an error or an output
pass_context
Without, setted It to false, setted It to true none of them works?
remove it completely
I tried that either, didnt fix it.
didn't say it would fix it, you just don't need it 👀
Oh ok lol
class aiohttp.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, version=aiohttp.HttpVersion11, ...)```
The class for creating client sessions and making requests.
I put In an title, description, and changed It to clientsession but still no output
override the __init__ and pass in the message you want inside the super’s init
or you could just subclass
and pass in when you call the class
@ionic wadi
I changed that too
async def meme(ctx):
embed = discord.Embed(title="Mempie", description="Hier is wat oog vermaak... Vers van reddit.")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
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.
Your custom exception needs to be a subclass of any built in exception classes
no, any built in exception class (TypeError, Exception, BaseException, ...)
who subclasses BaseException
that was an example
async def meme(ctx):
embed = discord.Embed(title="Mempie", description="Hier is wat oog vermaak... Vers van reddit.")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
Anyone who understans why theres nothing
No error, no output
understands* I suck at apis lol
you’re not even using the api correctly
where the textbook went
the reddit api requires authentication
ah
what you’re using there is json endpoints you’re not supposed to use
the ratelimits for the json api are high
is this guide up 2 date?
is there a way i can increase the width of an embed
Hi
nope, they are auto scaled, this depends on the size of the screen
Hi
how do i search for music and play
certain music
like the first video
i want name to be passed, not url
can someone recommend a good tutorial about a d.py ticket system such that when you react to the message, it opens a new for the person and the mods to chat in? with mongodb
there is a max width... which's value im not sure of
one way to increase this would be to create an empty image of x width and set it as footer?
?
it says 1.0
noone will suggest a tutorial, rather discourage you from doing a tut
There are none, u just figure out how it will work then implement it and help urself w docs
i was actually confused about the db stuff so yeah
ig i'll find something which is about mongodb
thats for version 1, and you probably want to look into the documention of dpy itself
discord.py server has it ig
i can make the ticketsys myself, just need to see how mongodb works with py
U need to know how to create, read, update and delete stuff in db
yeah im learning how to do that
why are you using mongodb?
Make a separate data access object class w methods like insert_member or delete_member and implement db stuff there
It’ s easy to use, u dont need to mess w transactions and connection pools
And It’ s fast w lots of data
its usage for discord bots is discouraged
Guys it is possible to change the name of the bot with a command or not ? and if its possible how
Yea but if ur learning It’ s easier

U can change nickname
Or if u wanna make ur life hell u can use selenium to log into dev portal and change the name, but it gonna last long and It’ s dumb
await edit(*, reason=None, **fields)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
Docs
async def on_member_leave(member):
channel = bot.get_channel(858699731928219668)
embed=discord.Embed(title=f"Jammer {member.name}", description=f"{member.name} is {member.guild.name} verlaten.... :sob: ") # F-Strings!
embed.set_thumbnail(url=member.avatar_url) # Set the embed's thumbnail to the member's avatar image!
embed.set_footer(text="Bot powered by @APotato#1900")
await channel.send(embed=embed)```
I dont get an output or an error, why?
its on_member_remove
On member remove not on member leave
Oh thanks
@bot.event
async def on_ready():
print('The bot is logged in.')
print('Ready!')
print('Logged in as ---->', bot.user)
print('ID:', bot.user.id)
await bot.change_presence(activity=discord.Game(name=f"Start up"),
status=discord.Status.idle)
await asyncio.sleep(60)
await bot.change_presence(activity=discord.Game(name=f"@cadmus help"),
status=discord.Status.do_not_disturb)
startTime = time.time()
@bot.command(pass_context=True)
async def uptime(ctx):
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
embed = discord.Embed(colour=0xc8dc6c)
embed.add_field(name="Uptime", value=uptime)
embed.set_footer(text="<bot name>")
try:
await ctx.send(embed=embed)
except discord.HTTPException:
await ctx.send("Current uptime: " + uptime)
Error
Ignoring exception in command uptime:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 38, in uptime
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
NameError: name 'startTime' is not defined
btw can i use a library like tensorflow with d.py so i can make a chatbot which works in a specified channel?
global startTime on on_ready
or better, make it a bot variable bot.variable = value
also dont do shit in on_ready since its triggered multiple times :(
U can but it gotta be async
Like It can be made
hmm thats nice
global start ??
im guessing its gonna be pretty hard
but its hard and you should probably do a couple of easier projects first
you need to make startTime a global variable
how ?
Well machine learning is lot of maths and stuff so It’ s hard yea
can I send my code here?
read my first message
!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.
!paste
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.pydis.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.
if its bigger ^^
U using startTime in diff function that y defined it in
no. I mean, are you in the middle of something?
basically
i want these 2 embeds to be of same width
lotta people ask here and anyone can answer, there isnt any fixed thing to who can ask/asnwer when

םל

why isn't it letting me to send my code?
!paste
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.pydis.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.
Bro if u do the same as in dpy server istg
but, that is the thing that do not work...
uhm.
use the same embed 
i doubt there is a good way to achieve what you want without hard coding it
what is istg?
I swear to god
U cant just post whole ass code then ask ppl to figure out whats wrong w it
Yk?
now that you mention it...
HAHA
so how do I ask for help without posting a gaint block of code?
A simple guide to getting help
In order for us to help, we need relevant information.
Have an error/issues? Provide the full traceback output. Show code around the error, and any relevant code.
Something happening different than expected? Explain what's expected, then compare to what is actually happening.
Keep in mind that we are not you, we cannot read your mind, and saying something like "My code doesn't work!" or "I have an error." or "This code is broken, why?" or "Can somebody help me?" gives absolutely nothing, and is just annoying. You must provide information that we need in order to look into whatever your question is.
As a courtesy to others, please refrain from pasting large codeblocks into chat. If it's big enough, you will annoy other users in the channel. Please use services such as https://hastebin.com/, https://gist.github.com/ or https://ghostbin.com/.
If you don't know Python, hop into testing and run ?tag lp. Without a solid knowledge in Python, we cannot properly assist you. Yes, it will take months. Coding isn't just gluing text together. It takes time and patience — months or years.
Like, u gotta post the part of code that is not working and tell ppl what u tryna achieve and which part is not working
U posted whole command and said It’ s not working
In dpy server
^
@commands.Cog.listener()
async def on_message(self, msg):
data = get_leveling_data()
await create_leveling_acc(user, guild)
xp = data[str(guild.id)][str(user.id)]["xp"]
lvl = data[str(guild.id)][str(user.id)]["lvl"]
to_the_next_lvl = data[str(guild.id)][str(user.id)]["to_the_next_lvl"]
xp += 1
print("test")
if xp > to_the_next_lvl or xp == to_the_next_lvl:
data[str(guild.id)][str(user.id)]["xp"] = xp - to_the_next_lvl
data[str(guild.id)][str(user.id)]["to_the_next_lvl"] = round(to_the_next_lvl ** 1.02)
data[str(guild.id)][str(user.id)]["lvl"] += 1
with open("leveling.json", "w") as f:
json.dump(data, f)
how do i hard code it
you cant
its on discord's side
you dont have any control over embed sizes unless you add more characters
is there a way i can add invisible characters
there is a zero width space
how do i do that
google it
okay
for what overwrites_for is used?
for getting overwrites
@hasty iron blanket can you help me here please? I'm trying to add bot into the dropdown but I keep getting error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() takes 2 positional arguments but 3 were given 3 were given for line view = DropdownView(self, bot)
Another question i need to unrank someone with a command like +unrank that removes him all his ranks
what is self
Didn't you already ask?
also the self argument is implicitly filled
of the init
yeah, why did you pass in self
just pass in bot
no i dont think so
you also didnt pass in bot into Dropdown
Try iterating through all of the Member.roles and member.remove_roles(add what you iterated through here)
of course, make an error handler
and i don't think you should try it on yourself
if you are the server owner
self.add_item(Dropdown())
Oh
i meant that
hey so im making a antinuke bot right now, currently if you create multiple channels at the same time (using a nuker) it will only delete 1 or 2 channels, would anyone know how to delete all channels made in a certain time frame (eg. the last 5 seconds)
I see that, my bad
Hey I'm trying to make a guess the number game and it works but when someone else message when im playing thres and error
@bot.command(aliases=["gtn"])
async def guess(ctx):
number = random.randint(1,100)
await ctx.send(f'guess a number between 1 and 100 \nYou have 5 tries')
ng = 0
while ng < 5:
response = await bot.wait_for('message')
guess = int(response.content)
if guess == int(response.content):
if guess>number:
await ctx.send('try guessing lower')
if guess<number:
await ctx.send('try guessing higher')
if guess==number:
await ctx.send('you got the number')
return
@bot.event
async def on_command_error(ctx,error):
if isinstance(error,commands.MissingRequiredArgument):
await ctx.send("Put in all required arguments please")
if isinstance(error,commands.errors.CommandInvokeError):
await ctx.send("thats not a number, your game has ended")
i know the error handling is kinda dum but it works for now 👀
you need to add a check
to make sure the bot only responds to your message and no anyone elses
how to add that
return true if the author is command user and channel is the channel where command is used
make a function
^
ohh ok thanks
or lambda 
or that, sure
whats lambda
okay thanks 😄
guys i have this snipe code but it's not working idk why
@commands.command(name="snipe")
async def snipe(self, ctx: commands.Context):
"""A command to snipe delete messages."""
if not self.last_msg:
await ctx.send("There is no message to snipe!")
return
author = self.last_msg.author
content = self.last_msg.content
embed = discord.Embed(title=f"Message from {author}", description=content)
await ctx.send(embed=embed)
name argument of command() is useless
not really
what if you want symbols in your command name
it's used to indicate the command name if you don't define the async def as the command name
in this case
in this case what
what
did you understand what i said
yes
any error?
you cant have symbols in function names
but he doesn't...
are we talking generally?
no
or his specific case
yes
it puts that +snipe dont exist
the command
have you loaded the cog?
i think so
async def send_bot_help(self, mapping):
ctx = self.context
hel = []
bot = ctx.bot
for cog, cmds in mapping.items():
if cog and await self.filter_commands(cmds, sort=True):
hel.append(cog)
embed = discord.Embed(description=bot.description,color=discord.Color(colour))
for idx in hel:
embed.add_field(
inline=False,
name=idx.qualified_name.title(),
value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands()))),
)
await ctx.send(embed=embed)
```how do i do `await self.filter_commands(cmds, sort=True)` in **value*???
What exactly do you want to do?
help command
I know that but more what result
like now its sending help of cmd which the author cant use
its sending both usable and non usable
!d discord.ext.commands.Command.can_run this function will help with that.
await can_run(ctx)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
idk how to use this
Inside the function the command or context is passed.
ok where do i need to use this
in the value or in the loop?
It's a command attribute,
i am not understanding
allowed_cmds = await self.filter_commands(cmds, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
cmds refering to a list of all the bots commands.
'owner' object has no attribute 'can_run'
is owner a cog?
ya i have a cog
Try this ```py
allowed_cmds = await self.filter_commands(bot.commands, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
uh i am having problem with database and this bot .. kinda i cant explain
Not in a for loop!
eh
Atleast give us a general idea.
Not meant for you.
uk database?
yea i got that
idk i just started databases today and .. :/
What do you mean? Like the chartype?
uh just see the code
in the value i did
Okay what database are we dealing/ what module.
msql.connector
I'm familiar with that module
Ello panda
Do you get an error?
Hello
Traceback (most recent call last):
File "main.py", line 22, in <module>
from help import HelpCommand
File "/home/runner/Trust-
Traceback (most recent call last):
File "main.py", line 22, in <module>
from help import HelpCommand
File "/home/runner/help.py", line 35
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
^
SyntaxError: invalid syntax
for cog, cmds in mapping.items():
if cog and await self.filter_commands(cmds, sort=True):
hel.append(cog)
embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
allowed_cmds = await self.filter_commands(bot.commands, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
for idx in hel:
embed.add_field(
inline=False,
name=idx.qualified_name.title(),
value=", ".join(map(lambda x: f"`{x}`", allowed_cmds),
)
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=bot.user.display_avatar)
embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
await ctx.send(embed=embed)
import discord
from discord.ext import commands
import mysql.connector
database = mysql.connector.connect(
host="",
user="",
passwd="",
database="testing")
cursor = database.cursor()
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')
bot = commands.Bot(command_prefix='.')
@bot.command()
async def test(ctx):
await ctx.send("Name")
ans = await bot.wait_for('message')
strans = str(ans.content)
sql = f'INSERT INTO testing (name) VALUES (%s)'
val = (strans),
cursor.execute(sql, val)
await ctx.send('added to database')
the first one without discord.py works and the second one.. it says added to database but doesnt show in database
huh?
MySql is not asynchronous
whats asynchronous..
This means if you make a large query , your bot will be blocked
!async
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of which coroutine is being run is switches periodically to allow all of them to run, giving the appearance of running at the same time. This is different to using threads or processes in that all code is run in the main process and thread, although it is possible to run coroutines in threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function this would have raised an exception like: SyntaxError: 'await' outside async function
To run the top level async function from outside of the event loop we can get an event loop from asyncio, and then use that loop to run the function:
from asyncio import get_event_loop
async def main():
await something_awaitable()
loop = get_event_loop()
loop.run_until_complete(main())
Note that in the run_until_complete() where we appear to be calling main(), this does not execute the code in main, rather it returns a coroutine object which is then handled and run by the event loop via run_until_complete().
To learn more about asyncio and its use, see the asyncio documentation.
@cloud dawn idk why this SyntaxError is coming
uh .. mysql doesnt work when using async?
ct
x?
It will work but its going to block your bot
Atleast not my code :D
But i don't see anything weird either, maby embed too long.. don't think so... hm
This means your bot will not respond
bot did ig..
How many guilds will this bot be in?
Until the request is completed
ctx = self.context
not getting anything
Make a large request and then you will see it yourself
huh.. :/
guilds = servers
just 1
Then mysql will be just fine, let's not worry about async programming for now.
Yeah then its fine
uh what should i do tho..
Why are you using f strings
And val = (strans),
Button(style=ButtonStyle.grey, Label="1")
```Why does this say `Button got an unexpected argument 'Label'`
That is wrong
uh i had that used for str(ans) but it gave error i forgot to remove
I'm assuming the config is defined.
uh?..
Can't help you without context.
it gives error if i don use that when the column of the database is only 1
should i send more?
Could you provide the full error?
label*
there aint any error
Atleast give me a general idea, something to work on, code, traceback of error.
just a minute
Traceback (most recent call last):
File "main.py", line 22, in <module>
from help import HelpCommand
File "/home/runner/-Bot-2/help.py", line 28
allowed_cmds = await self.filter_commands(bot.commands, sort=True, key=lambda command: await command.can_run(ctx) and not command.hidden)
^
SyntaxError: 'await' outside async functio
@upbeat otter label should all be lowercase
ohthenx
..
...
...
....
Is the value formatted right? The tuple.
formatted?
not starting a chain, just didn't know what they meant
..
Lemme rewrite this then.
Ye
I thought my friends were weird, u guys started with the dot thing too 😂
ok
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')
ok so this works
@frosty prairie what is the problem?
lol
@bot.command()
async def test(ctx):
await ctx.send("Name")
ans = await bot.wait_for('message')
strans = str(ans.content)
sql = f'INSERT INTO testing (name) VALUES (%s)'
val = (strans),
cursor.execute(sql, val)
await ctx.send('added to database')
``` but this doesnt
it doesnt give error .. but it just says added to database and doesnt add
to use buttons, i should import discord_components right?
print ans please
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
thenku
its a long detailed of the message..
Try this```py
@bot.command()
async def test(ctx):
await ctx.send("Name")
ans = await bot.wait_for('message')
strans = str(ans.content)
sql = f'INSERT INTO testing (name) VALUES (%s)'
val = (strans,)
cursor.execute(sql, val)
await ctx.send('added to database')
???
u said print ans

ah ok
!e ```py
print('ans')
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
ans
.......?

@cloud dawn how it worked 
nope it sends all commands now. all cmds in all cogs
wait a well it didnt work 
!e print(type(('1'))); print(type(('1', )))
@maiden fable :white_check_mark: Your eval job has completed with return code 0.
001 | <class 'str'>
002 | <class 'tuple'>
ah gotcha
Yeah mysql.connector takes tuples not str
every module takes in tuples
it didnt work tho..
me a postgre user no
You just told us it worked 
@cloud dawn
without async def
it doesnt.
What do you want?
Like per cog list in a list?
no bruh
u know how the default help cmd work?
its only send the help of cmd which can be used by the author
mine sends all cmd of the bot
Need more info🐼
Yeah since you are prob the owner
no bruh
all ik is```py
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')
this works
```py
async def test(ctx):
await ctx.send("Name")
ans = await bot.wait_for('message')
strans = str(ans.content)
sql = f'INSERT INTO testing (name) VALUES (%s)'
val = (strans),
cursor.execute(sql, val)
await ctx.send('added to database')
this doesnt(it executes added to database but doesnt actually add and returns no error)
a normal member can see owner only cmds too
Can you send your current code?
..
for cog, cmds in mapping.items():
if cog and await self.filter_commands(cmds, sort=True):
hel.append(cog)
embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
for idx in hel:
embed.add_field(
inline=False,
name=idx.qualified_name.title(),
value=", ".join(map(lambda x: f"`{x}`", allowed_cmds)),
)
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=bot.user.display_avatar)
embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
await ctx.send(embed=embed)
..
What is that for loop on top?
No sorry, we can solve it here, i'm thinking about both problems 😌
oka..
And why?
So basically trying to make a calculator but whenever i try to click a button it says: Interaction failed, Here is the current code:
@client.command()
async def calc(ctx):
m = await ctx.send(content="Loading Calculator")
expression = "None"
delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
await m.edit(components=buttons, embed=e)
while m.created_at < delta:
res = await client.wait_for("button_click")
if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
expression = res.message.embeds[0].description
if expression == "None" or expression == "An error Occurred":
expression = ""
if res.component.label == "Exit":
await res.respond(content="Calculator Closed", type=7)
break
elif res.component.label == "←":
expression = expression[:-1]
elif res.component.label == "Clear":
expression = None
elif res.component.label == "=":
expression = cal(expression)
else:
expression += res.component.label
f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
await res.respond(content=None, embed=f, component = buttons, type=7)
if somebody can help plz
class HelpCommand(commands.HelpCommand):
def __init__(self):
super().__init__(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=True,
)
async def send_bot_help(self, mapping):
ctx = self.context
hel = []
bot = ctx.bot
owner = bot.get_user(862906093373751337)
for cog, cmds in mapping.items():
if cog and await self.filter_commands(cmds, sort=True):
hel.append(cog)
embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
for idx in hel:
embed.add_field(
inline=False,
name=idx.qualified_name.title(),
value=", ".join(map(lambda x: f"`{x}`", allowed_cmds)),
)
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=bot.user.display_avatar)
embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
await ctx.send(embed=embed)
Anyone?
debugging...
I'm trying to upload a png to discord
file=discord.File("content.png")
embed.set_image(url="attachment://content.png")
await ctx.send(file=file,embed=embed)
but I keep running into errors like:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: _request() got an unexpected keyword argument 'form'

file path
its located in the same folder as the code
I can just use the file name...
:/
!d discord.Guild.member_count
then idk
member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
i khnow it's easy
..
Help in #help-candy please
I'm not sure but set filename kwarg in discord.File
And use attachment://filename instead
Could you maby put all the code of this file inside a paste?
Then i will try and fix it.
what is a new lib for discord
.
file_lol = discord.File("content.png",filename="kwarg.png")
embed.set_image(url="attachment://kwarg.png")
await ctx.send(file=file_lol, embed=embed)
Still same error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: _request() got an unexpected keyword argument 'form'```
total_users = len(list(filter(lambda user: not user.bot, bot.users)))
Somebody Help in #help-candy please.......
uh..
thats the full code
what is a new lib to replace\ discord.py
disnake is the most promising rn
thank you
Since member will be the object
panda forgor me 
Okay i will try something.
ok
Anybody can help in #help-candy please???
No i'm helping pog first, could you maby create a help channel? then i will join you there
!e
class A(Exception):
def __init__(self, message, user_id: int):
self.user_id = user_id
return super().__init__(message)
raise A('donno', 123)
@pale turtle :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 4, in __init__
004 | TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Uh what
thx ❤️
!e
class A(Exception):
def __init__(self, message, user_id: int):
self.user_id = user_id
return super().__init__(message)
raise A('donno', 123)
@pale turtle :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | __main__.A: donno
There I think that's it
uh i ping u tomorrow ig.. its late night
known error? ```py
Traceback (most recent call last):
File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\help.py", line 848, in command_callback
return await self.send_bot_help(mapping)
File "C:\Users\eboss\Documents\GitHub\spotipy\commands\help.py", line 141, in send_bot_help
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
AttributeError: 'Member' object has no attribute 'display_avatar'
That's also fine.
nope. what version did u use?
mine is 2.0.0a
Ah mine is stable.
!e
class A(Exception):
def __init__(self, message, user_id: int):
self.user_id = user_id
return super().__init__(message)
try:
raise A('donno', 123)
except A as error:
print(error.user_id)
I think this might be what you need? @tawdry perch
@pale turtle :white_check_mark: Your eval job has completed with return code 0.
123
thats why u try ctx.author.avatar_url
I will just make the filter command list then you can use that, same concept.
sure
Also is that "owner" your id?
If so you can just do bot.owner to get the id :)
ya
reallly but everytime i do that i get
bot.owner
AttributeError: 'Bot' object has no attribute 'owner'
Did you define yourself in the constructor?
Also ```py
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
nope
Ah you need to do that for it to work.
for me
Try this```py
class HelpCommand(commands.HelpCommand):
def init(self):
super().init(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=True,
)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
owner = bot.get_user(862906093373751337)
embed = discord.Embed(description=bot.description,color=discord.Color(0xffffff))
allowed_cmds = [command.name for command in bot.commands if not command.hidden and await command.can_run(ctx)]
embed.add_field(
inline=False,
name='test',
value=", ".join(allowed_cmds),
)
embed.set_author(name=ctx.author,icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=bot.user.display_avatar)
embed.set_footer(text=f"Made with ❤️ by {owner}",icon_url=owner.display_avatar)
await ctx.send(embed=embed)
oh prob error at idx.qualified_name.title()
Edited
That looks better
before
value=", ".join(map(lambda x: f"`{x}`", filter(lambda x: not x.hidden, idx.get_commands())))
Hmm and you want that again?
i want the same format but like it should only show the cmds that can be involved by the author
"same" = this ^^^
I have an idea how to do this and make it more readable along the way.
tell
I will code it hold on...
Hello guys how can i do a +dm that dms a member when i do it pls
Still coding..
this: tmp = tmp.strftime("%B %Y %H:%M:%S") await ctx.send(f"l'account di `{member}` è stato creato nel `{tmp}`")
make: l'account di Hik#9778 è stato creato in data: December 2016 22:57:26
how can i add the number as 26 December 2016 ?
still here,me also finding a way
What did you have to do if a @bot.event caused your code to break? (i.e your commands don't work etc)
@help.group()
async def page(ctx, number):
page1 = ["Exercise 1","Exercise 2","Exercise 3","Exercise 4","Exercise 5","Exercise 6","Exercise 7","Exercise 8","Exercise 9","Exercise 10","Exercise 11","Exercise 12"]
page2 = ["Stuff", "Stuffa", "Stufdsds"]
page = "page" + number
await ctx.send(page)
I know why this isn't working, but I don't know the solution
-
What I expect it to do is print the variables
page1orpage2based on the page number the user input. -
The error is when I do
page = "page" + number, they are considered as strings instead of a variable
Finally code really was being a bish
class HelpCommand(commands.HelpCommand):
def __init__(self):
super().__init__(
command_attrs={
"help": "Shows help about the bot, a command, or a category",
},
verify_checks=True,
)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
embed = discord.Embed(description=bot.description, color=discord.Color(0xffffff))
for cog, commands in mapping.items():
try:
if cog.get_commands():
embed.add_field(
inline=False,
name=cog.qualified_name,
value=", ".join([f"`{command.name}`" for command in cog.get_commands() if not command.hidden and await command.can_run(ctx)]),
)
except(AttributeError):
# Error for if the cog is a cog but not quite a cog like Help
pass
await ctx.send(embed=embed)
wait let me try
what did it send for you
DM'ed
commands that aren’t inside a cog won’t appear with that help command
and why cog.get_commands(), you already have commands
and rather than checking for an attribute error, you could just check if cog is None
I was using ```py
channel = ctx.channel
def check(msg):
return msg.content == 'confirmar' and msg.channel == channel
await client.wait_for("message", check=check)
await channel.clone(reason= "Nuke Channel")
await channel.delete()
Does anyone know how to fix? It was for a nuke command
Try await self.client.wait_for("message", check=check)
ok thks
#help-cupcake message
@storm zodiac if your bot is subclassed you can do it the same way
discord.Guild.premium_subscribers returns a list of discord.Member. You can do await ctx.send(member.name for member in ctx.guild.premium_subscribers)
that would send a generator object
await ctx.send('\n'.join(member.name for member in ctx.guild.premium_subscribers))
use that instead
Oh wait right.
What's game
if you want to "solve" then learn python
can u help me ?
i dont think i can
can you post a snippet @slate swan
the line is too long too. Ever consider abiding the 20 year old rule (pep 8)?
ive been trying everything but it doesnt work. How can i make the emojis in place?
does message.content no longer work?
it does
why?
I'm sorry I figured it out. i had message.contents
For some reason people can still tag roles even though i have it disabled in the channel permissions. can't figure out why. I've checked their permissions and roles as well
hey so my bot has a covid command
for example
if it shows this number
482292
how do i make it so it puts the commas
with
if len(checks) < 10:
for doc in range(len(checks)):
mem = ctx.guild.get_member(checks[doc])
name = mem.display_name()
print(name)
else:
for doc in range(10):
mem = ctx.guild.get_member(checks[doc])
name = mem.display_name()
print(name)```
I'm getting
```File "/home/turtle/dusk-beta/cogs/economy.py", line 429, in baltop
name = mem.display_name()
TypeError: 'str' object is not callable```
change mem.display_name() to str(mem.display_name())
same thing
Anyone know how to get a print out of all permissions in a channel
if you want for a particular user
i want my program to tell me what message caused an error but this doesn't work and says the object "CommandNotFound" is not subscriptable py await kevlu8.send(error + " when command " + str(ctx.message) + " was run.")
post full function
!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.
show full code maybe
@client.command()
async def stats(self, ctx):
embed = Embed(title="Bot stats",
colour=ctx.author.colour,
thumbnail=self.bot.user.avatar_url,
timestamp=datetime.utcnow())
proc = Process()
with proc.oneshot():
uptime = timedelta(seconds=time()-proc.create_time())
cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user)
mem_total = virtual_memory().total / (1024**2)
mem_of_total = proc.memory_percent()
mem_usage = mem_total * (mem_of_total / 100)
fields = [
("Bot version", self.bot.VERSION, True),
("Python version", python_version(), True),
("D iscord.py version", discord_version, True),
("Uptime", uptime, True),
("CPU time", cpu_time, True),
("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True),
("Users", f"{self.bot.guild.member_count:,}", True)
]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
removed every self in that code
@client.command()
async def stats(ctx):
embed = Embed(title="Bot stats",
colour=ctx.author.colour,
thumbnail=bot.user.avatar_url,
timestamp=datetime.utcnow())
proc = Process()
with proc.oneshot():
uptime = timedelta(seconds=time()-proc.create_time())
cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user)
mem_total = virtual_memory().total / (1024**2)
mem_of_total = proc.memory_percent()
mem_usage = mem_total * (mem_of_total / 100)
fields = [
("Bot version", bot.VERSION, True),
("Python version", python_version(), True),
("D iscord.py version", discord_version, True),
("Uptime", uptime, True),
("CPU time", cpu_time, True),
("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True),
("Users", f"{bot.guild.member_count:,}", True)
]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
yes
the "thumbnail=bot.user.avatar_url," says "positional argument follows keyword argument"
cuz thumbnail isnt a argument in a embed its a method
member = ctx.author
em = discord.Embed(
title=f"Suggestion",
description=
f"{reason}",
color=0x00a8ff)
em.set_author(name=f"{ctx.author}", icon_url={member.avatar_url})``` ```py
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
``` What am I doing wrong here?
well what does your error say you're doing wrong?
member doesn't have avatar_url, but the docs tell me to use member?
Or user in that case
try user then 🤷♂️
whats with curly brackets around member.avatar_url
Was just testing it, it shouldn't make an impact
I tested it many times and it gave me the same error as without the brackets so idk
How would I define member then...?
member = [what you want to define it as here lol]
a discord.Member object
member = ctx.author``` Yes, no?
that's seems correct
Same error :P
why dont you just type out ctx.author? lol
Because that's the same error lol
if thats what you want it to be
else:
member = ctx.author
em = discord.Embed(
title=f"Suggestion",
description=
f"{reason}",
color=0x00a8ff)
em.set_author(name=f"{ctx.author}", icon_url=member.default_avatar.url)``` Gives me the gray icon
actually looks fine to me
what is this even for? userinfo command?
that should be fine
Basically, yes
Sure, I can try it :P
try member.avatar.url
I've done everything the documents said, I'm on 2.0 so that could be a bug not sure though
from datetime import datetime
from typing import Optional
from discord import Embed, Member
@client.command()
async def userinfo(ctx, member: Optional[Member]):
target = member or ctx.author
embed = Embed(title="User information",
colour=target.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=target.avatar_url)
fields = [("Name", str(target), True),
("ID", target.id, True),
("Bot?", target.bot, True),
("Top role", target.top_role.mention, True),
("Status", str(target.status).title(), True),
("Activity", f"{str(target.activity.type).split('.')[-1].title() if target.activity else 'N/A'} {target.activity.name if target.activity else ''}", True),
("Account Made", target.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
("Joined Server", target.joined_at.strftime("%m/%d/%Y %H:%M:%S"), True),
("Boosting?", bool(target.premium_since), True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
Same error lol
wait really?
Yeah that's why I'm confused
it should work tho.. hmm
try passing it to type
bro thats so old!
is it, it would make sense
2.0 is the beta
it's actually already released before the end of discord.py so discord.py 2.0 is the latest
discord.py 2.0
idk just try my code
not python 2.0 lol
is 3.9 even a dpy version that have been made?
and if its the beta then it could be a bug
i thought he was talking about python
not discord.py lol
i think im dying from hunger
@hollow agate
can you try
else:
member = ctx.author
avatar = member.avatar.url
em = discord.Embed(
title=f"Suggestion",
description=
f"{reason}",
color=0x00a8ff)
em.set_author(name=f"{member.name}", icon_url=avatar )
```as a test
normally it should work
that works 


My brain

ok here:
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Missing parameters! Run :help to see correct parameters. :kek: :emoji_37:')
elif isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have permission to run this command. :thonk: :Supper:")
else:
guild = bot.get_guild(855275010556821524)
kevlu8 = guild.get_member(458684594703695872)
if kevlu8 == None:
kevlu8 = guild.get_member_named("kevlu8#5240")
try:
await kevlu8.send(error + " when command " + str(ctx.message) + " was run.")
print(str(ctx.message))
except:
splitatchar = 2000
one, two = error[:splitatchar], error[splitatchar:]
try:
await ctx.send(one)
await ctx.send(two)
except:
mid1, mid2 = two[:splitatchar], two[splitatchar:]
try:
await ctx.send(mid1)
await ctx.send(mid2)
except:
await kevlu8.send("Bro there's an error go check console")
print(error)```
you silly goose
this line is not whats causing the issue
check the traceback again
and tell us which one from here causes the issue
yeah when someone runs a command that isn't missingrequiredargument or missingpermission, i want to get dmed by my bot telling me what the error is and what caused it, but the line py await kevlu8.send(error + " when command " + str(ctx.message) + " was run.") gives me an error, "unsupported operand types for commandnotfound and str" in str(ctx.message)
@slate swan
your error was "CommandNotFound" is not subscriptable
and what it means is that you tried to use square brackets with some object that doesn't support it
hence i am sure this isnt the line thats causing this issue
error[:splitatchar]
is the cause
most likely
alright i'll try getting rid of that
it works when i only do py await kevlu8.send(error)
but you're right, this also gives an error
error = str(error)
put this somewhere at the top of the function
see if its fine now
thanks it works now
but it sends me this, how do i get the exact message that was sent? (for context i sent :e which isnt a command to trigger commandnotfound)
no, it gives the above output
ctx.message is the discord.Message object, you want the content attribute of said object
!d discord.Message.content
The actual contents of the message.
oh, i see, thanks a lot
Would anyone like to use my API to create a command?
Here is the Docs, DM me if you do use it.
use ctx.message.content
instead of ctx.message
as andy said
That is to get the message string itself.
yes
i know

I know that you know. lol
and as far as this messy output, there doesn't seem to be any way to get the nicely formattable name of the error object
so just dont print it
alright, i see, thanks
you can still know which type of error is it
by using isinstance like you already do
for some types of errors
also i may seem stupid because it already has the command there but just in case there's a different error lmao
So I'm writing a discord bot for a server. One of them has 500+ users. The 2nd group (2 different bots) has over 6k users. I've heard about shards but can't really find the page in the wiki. Can someone give me a tl dr?
req = await bot.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
# If statement because the user may not have a banner
if banner_id:
banner_url = f"https://cdn.discordapp.com/banners/{user.id}/{banner_id}?size=1024"
how can i put this into a command
How would I make a command that sends how many times a certain word was said in a server
I know I have to check the message content
and use on_message but I just don't know how I would use that in a command
@client(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = [
discord.Embed(title='It is certain.'),
discord.Embed(title='It is decidedly so.'),
TypeError: 'Client' object is not callable
i imprted client
weird
plz help
You need @client.command(aliases=['8ball'])
Also this command wont do anything
could I get someone to make me a discord bot of my customs?
how do you remove a user's reaction on a message in the bot?
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Emoji "discord.Emoji").
If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
you may find devs in Fiverr for that
ok thx
how would i write aliases for a command
@commands.command(aliases=["ali","ases"])
I need some out of cost ones
No one would do that i guess
CommandNotFound error how i can get what command the user sent?
What's the best database to use?
PostgreSQL
How do I use it, like do I have to set it up on my pc or is it web-based?
Do you have to set it up on your pc
?
?
Like do I download it and set it up on my pc so it uses my personal storage, or is it web-based and uses their storage?
You need to install it but it dont use ur storage
Oh cool!
ok question
i have a ban command coded
it works with ids and mentions
but it doesnt work with ids of people not in the server
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
await member.ban(reason = reasonlol)
await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
any thoughts?
Nevermind
Wait
Why are u using has_any_role
if its just one role
ok
Youre trying to ban ppl not in the server?
correct
Use discord.Object
with a userid
and pass it in Guild.ban
excuse me what
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
`x == y` Checks if two objects are equal.
`x != y` Checks if two objects are not equal.
`hash(x)` Returns the object’s hash.
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
its fine
obj = discord.Object(pass id here)
await Guild.ban(obj)
Guild has to be a discord.Guild object
like ctx.guild
does this fetch the user even if the user is not in any mutual servers?
it should
Detailed discord.py resources?
Thanks you both
This is awesome 😎
Yeah
....
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
obj = discord.Object(pass id here)
await Guild.ban(obj)
await ban(user, *, reason=reasonlol)
await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
so like this?
Noo
^
You will have to edit the typehint
and Guild has to be a discord.Guild object, ctx.guild in your case
Remove that line below guild.ban too
@bot.command()
@commands.has_any_role("Staff")
async def ban(ctx,member:discord.Member,*,reasonlol):
await ctx.guild.ban(obj)
await ctx.send(f"{member.name} has been banned. Reason: {reasonlol}")```
Idk if Union works
No
heck
try
member: typing.Union[discord.Member, int] in your function arguments, then use isinstance to check if you got int or discord.Member, if int then pass it in discord.Object else pass member directly to Guild.ban
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Typehint member to commands.MemberConverter and you'll be able to ban them using IDs, Mentions, Name#Discrim, name, Nickname. @lunar grove
Typehint to discord.Member
Not if they are not in guild
Or discord.User
wut
no he wants to ban using id
That can take ID too
o
helllo guys, i asked for help in #help-bagel but MOnK told me to ask here.
i am getting this error
im thinking of making a discord.py invite tracker bot but i dont know where to start
start with telling the bots about the channel(s) in which it shd send the messages
like make a list or int
i finished that
idk much about these but in parenthesis i think we can pass the name of the variable user or joined member and we can use it
im asking of how to see who invited the user
like on_member_join(ctx, user)
docs is the best place
yea but how in the world do i check who invited the user
right-
check tat out
there is a way
helllo guys, i asked for help in help-bagel but MOnK told me to ask here.
i am getting this error
just anyone who help me ping me here and tell me how to get user at on_member_join im gonna read the docs
i searched 'invite' at the docs and nothing helps me
@granite prawn https://medium.com/@tonite/finding-the-invite-code-a-user-used-to-join-your-discord-server-using-discord-py-5e3734b8f21f
So you want to know who invited a specific user to your discord server? Don’t worry, this is quite a simple thing to do. By the end of the…
this may help
ill read it
ok
pls help me someone
Hello
hi
i am making a discord game like dank memer
making bank cmds
and using json database
and now i am getting this error
@slate swan
You're loading the json incorrectly
wait i am sending code
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.
Use databases
lmao , json for game database?
Hey, Im trying to help a streamer friend of mine. How would I make a bot that live reposts stuff from one channel into a channel on a diff server
mongo db will work?
You are a beginner so try with sqlite3 or postgresql
Json is not a database

Not postgres lol
Postgres isn't for beginners
Mongo Db is fine too but if you want to start out with DBs you.can use aiosqlite3
lmao
hobbit*
not really helpful
but then ill try
ok
thanks
do you know any video tutorials?
theres this thing called youtube you should try it
import discord
import random
TOKEN = ''
client = discord.Client()
@client.event
async def on_ready():
print('we have loggeed in {0.user}'.format(client))
client.run(TOKEN)
In mine i have the token there ofc but the bot is not logging in why?
you put your client.run(TOKEN) inside of your on_ready function, it needs to be outside
Thanks
np, good luck!
!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
uk mysql?..
what is banned_users
Probably do something simpler to improve your python first 🙂
ok
Anyway you can see there's no variable called banned_users previously in the code
what should i do then
yes
Don't
why
Ya watching a tutorial youtube video and copying everything down isn't the way to learn
This is a better tutorial @late echo
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.
ok
I learnt from Lucas.
i need unban
But most of the people just copy the code... That's why we discourage seeing vids
i know how to make a kick,ban and more.
i learned not copyed
he explained me
everything
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
Ah right. I used to c&p then pause the video and change the code as much as I can.
Ah
pls tell me a alternative
how to make a unban command
get the Id of the person you are trying to unban and pass it in discord.Object(id here) then pass this object in Guild.unban
No
that's a bad way of doing it
^ use this
obj = discord.Object(id)
await ctx.guild.unban(obj)
where should i put it
id=id``` iirc
uhh that's all you need to do in that command after defining function
user = discord.Object(I'd=I'd)
await guild.unban(user=user)
@grim oar
👍
i mean, it can be a pos arg
ye ^
try this instead
..
async def acceptapplication(self, ctx, message: discord.Message):
guild = str(ctx.guild.id)
applicationchannel = self.bot.get_channel(self.applicationchannel[guild]['applicationchannel'])
id = message.id
msg = await applicationchannel.fetch_message(id)
applicant = msg.author
await msg.reply(f"**Accepted.\nWelcome to the clan.**")
await applicant.send("You have been accepted to the clan.")
@waxen granite
uk mysql?
okay
what
u know mysql?
partially
uh ..
Why are you fetching the Message, you already have it
yeah why do you fetch it actually. Kinda curious too
async def acceptapplication(self, ctx, message: discord.Message):
guild = str(ctx.guild.id)
applicationchannel = self.bot.get_channel(self.applicationchannel[guild]['applicationchannel'])
applicant = ctx.author
await msg.reply(f"**Accepted.\nWelcome to the clan.**")
await applicant.send("You have been accepted to the clan.")
sql = 'INSERT INTO testing (name) VALUES (%s)'
val = ('idjsfnd'),
cursor.execute(sql, val)
print('done')
this works
async def test(ctx):
await ctx.send("Name")
ans = await bot.wait_for('message')
strans = str(ans.content)
sql = f'INSERT INTO testing (name) VALUES (%s)'
val = (strans),
cursor.execute(sql, val)
await ctx.send('added to database')
this doesnt(it executes "added to database" but doesnt actually add and returns no error)
..
what engine are you using?
is that innodb?
its mysql
do you have phpmyadmin?
is there a way to send dm to a person whose name is on the embed.set_author?
@frosty prairie just add this after the execution. <connection>.commit()
why?
wait no, can you elaborate?
well nvm, it is just complicated :3
i mean you can but why?
oka..
make sure to replace <connection> with whatever variable you're using for the connection
actually nvm. sounds like you have myisam engine
..
indent it and try it
yeah
can u like .. just give a example of mysql being used with discord.py .. then ig i can do without problem :/
yeah i seperate mine from discord.py and make a module
wait
check this.
This is the module i use to simplify my code on mysql parts. I didn't finish it but it should work
ngl this should go to #databases
@lusty swallow it workeddd
what did you do
it was working when it was outside async but didnt work when inside async so i kept here..
tab like u said
what?
uh..
ofc it's supposed to be included at the async
why it worked..
sounds like you have innodb engine too
i mean .. without discord.py, while using just mysql it worked but while engaging with discord.py it didnt work so i kept here
consider installing phpmyadmin
is there any command i can type in sql shell? to find the engine
wait let me check
aighhtt
@frosty prairie
SHOW TABLE STATUS WHERE Name = 'table'
yee innoDB
If anyone could help that'd be great.






