#discord-bots
1 messages Β· Page 1009 of 1
Same
how can i make it so that the bot spams a message to someone
dont
ok but what if i was trying to test smth
Doesn't seem like something we would help with
Why would you need to test message spam
Due to rule 5 and all
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
F
:>
you should learn python before starting discord bots
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ik, i did a basic basic 1 hour thing, ik its barely anything, its just i thought of a discord bot that wld be rlly helpful, and i just wanna get it made without havin to pay π
i got pretty far, but was using if message.content.lower() instead of doin things properly π now i wanna move it all to slash commands, started doin that but cant thigure out hybrid and slash π
srry xD
so you want hybrid or slashes?
i wanna b able to do slash and prefix, and was told to use hybrid commands or somma
i have to write like 20+ pages ;-; (homework)
as a last resort i cld just do two of each comand and set one set to slash and one to prefix π but i dont think thats the way
daang, what subject?
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py refer to this, then refer to this
@bot.hybrid_command()
async def ping(ctx):
await ctx.send("pong")
sst?
psst
it is
tf is civic now
do you mean political science or smth?
or am i getting it wrong
ye political science
the study of the rights and duties of citizenship.
import discord
print(discord.__version__)
do this
okey, tysm!
sheesh weird name
2
3
u got it right
he left
3 textbooks? or supplementary incl?
500 or 600
Guess how many science books i have
3
No
4
No
I see, it should work then smh
2 private
flexes with just 2
both 1200 pages long uwu
For every book there's 2 types
A work book and a textbook
bio chemistry phy
So it just multiples
oh welp, so good to see that my life is easier
no
coming

mina or brad90 will come and ot us
I need to learn about ctypes
Ryuga would you know anything about ctypes
no i just know lil bit of cpp
AttributeError: 'Intents' object has no attribute 'message_content' 
is there any way to fix ? or make a new repl ?
did you just pip install discord.py?
dont use replit if you can
im 100%sure ive done that in past, lemme do again in case lol
in vs im not able to use sm commands
had already done that, still givin error π€
whys the think emoji frowning lol xD
you should update to the master branch to sue slash commands and hybrid commands, lemme get the command
aight
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
pog
hi
apparently i don't need it in 1.7.3 
π€·ββοΈ 
you cannot use slash commands or hybrid commands in 1.7.3 you need to upgrade to discord.py 2.0 using - pip install -U git+https://github.com/Rapptz/discord.py
aah tysm! prefix comand now working, i'm assuming i need to wait a few hours for slash command to work unless i do guild_id
right
its test_guilds fyi
or idk about hybrids nvm
why not make your own?
how do i get the bots in a guild
!d discord.Guild.members
property members```
A list of members that belong to this guild.
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
aight thanks
iterate through the members in a guild and check which of those is a bot
bots = [member for member in Guild.members if member.bot]
thanks
oh dang, i went too quickly, luckily i check back in, ty! π
π«
does this ever proceed any further π
its been an hour and a half
thats weird.. i updated code with guild, the prefix command has updated, but slash commands all stuck with old ones still.. i needa wait a bit even with guild specified?
hm wait
!d discord.ext.commands.Bot.hybrid_command
hybrid_command(name=..., *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to
the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
!d discord.app_commands.guilds
@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.
When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that itβs added to rather than being a global command.
Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.
Example...
its the same for hybrid commands too?
dpy is getting weirder every update
Yes
uh?
Ain't hybrid those commands which are text as well as app commands?
yeah π
wdym, im confused π
so wadda i put? and i dont put in hybrid_command()?
So how are they same as app_commands deco?
idk
I really wanted to ask, what is the first argument in hybrid commands an instance of?
guilds will only apply to the all commands
Context
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command")...
tf
lemme see
time to use hikari
Yea context is the first arg
no wonder discord.py is weird anymore π
im so confused π
How can I disable my cogs from accessing internal variables/functions
For example I don't want my cogs to be able to access the bot instance, etc
embed=embed needs to be embed=emb
Hunter help me π
that's all i noticed, otherwise idk because i havent worked with slash commands yet
well, 'TextChannel' object has no attribute 'respond'
yea?
How can I disable my cogs from accessing internal variables/functions. For example I don't want my cogs to be able to access the bot instance, etc
@slate swan was able to do prefix+slash with bridge xD
hm ic, cool
from what I just realized.....dpy's hybrid commands are weird, hikari would be better
π ye its confusin lol
huh, there is a thing to combine slash and normal commands?
:<
sadge
its glitch
E:\Computer Science β py -m Python.Code
relative import successful
E:\Computer Science β cd .\Python\
E:\Computer Science\Python β py -m .\Code\
C:\Program Files\Python310\python.exe: Relative module names not supported
@slate swan
yeah, got that
oh πΏ
so that makes sense, thats just how the notifications have been designed its not a glitch
it is
glitch
Sarthhhhhhhhakkkkkk, I need an opinion π
find me someone who ever got 10 notifs
yep
in google it show 1k+ pings
oh sure what is it
I got more than 6k once
whats that? hybrid_commands?
nuke
im talking about the app icon not your Discord Ui or the browser tab's title
idk, is hikari like more ideal for hybrid commands or discord.py? π and normal usage too, I'm really thinking of switching to hikari
browser discord ew
that, but was gettin confusing so i did:
import discord
from discord.ext import bridge
intents = discord.Intents.default()
intents.message_content = True
bot = bridge.Bot(command_prefix="!", intents=intents)
@bot.bridge_command(guild_ids=[956267961751044146]) # includes slash and prefix
async def hello(ctx):
await ctx.respond("Hello!")
https://docs.pycord.dev/en/master/ext/bridge/index.html if u wanna see more π
it really is better than dpy for anything, and yeah if you are planning to make hybrid commands hikari lightbulb is a super fine option
i can explain reasons if you want me to
yeah, was gonna use lightbulb with that
a couple if you can π
i made 2 commands that do the same thing one was slash and one was normal
π πΏ
-
as you already know easy hybrid commands
-
inbuilt paginators and utils support ( for someone popping in with "pycord has that too", check the docs and source before saying that)
-
Minimal OOP knowledge, plugins ( cog like stuff) can be used without explicitly Making a class
-
optional components, you can use native hikari components and discord.py views ( with miru) too
that suffice pretty much ig
Alright, gonna switch over to hikari for real now, cz discordpy is giving me a stroke now
and disnake doesnt even have hybrid cmds yet π
its worth it :p
and just let me know if you face any issues with it!
pretty sure they don't want to add it
probably will
but anyways i can refer to Gojo's source code
for sure, its very basic and simple π
yeah seems so
maybe
?
π it really is, other than extensions/starboard.py
if light was travelling through an opaque object
doesnt look too bad, I still can understand
alright, I have a question
Is it at all possible to set a status per-server for a bot?
I'm not seeing anything about it in the discord.py docs, but I might be missing something
you cannot do that
ah, okay
Worth a shot!
May I ask why? Is it just an API limit, or is there another reason for it?
if you know of course
status is global
no, but you can have that per shards
ok
per shard?
class discord.ext.commands.AutoShardedBot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") except that it is inherited from
[`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient "discord.AutoShardedClient") instead.
and now I'm going to dig into this rabbit hole heh
You can implement it yourself
It's quite simple
I'd rather just save my brain
You have one?
By quite simple he means it's truly quite simple
so what this does is?
which are
that's a lot
but what are shards, elaborate
what does this change in code perspective
I think it's about gateway
I see something
you have to give a shard id in order to change your presence in one server
!d discord.AutoShardedClient.change_presence
await change_presence(*, activity=None, status=None, shard_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example...
!d discord.Client.change_presence prolly doesn't have this?
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example...
Those are made automatically after around 2k guilds.
Shard are like running multiple instances of the bot.
Not automatically
botomatically π
What π
i want to check if the author has provided a url like ?d https://url.com
I recommend making commands instead of using the on message event.
oh okay
message.content is not callable
Import validators
If validators.url(the link):
What am I imagining 
So I wanna make a thing like if the user uses a?item medal and the command written in code is d?item(ctx) . . .
Is it possible to do like if users says a?item medal bot sends price=1m
And if the user uses a?item ribbon bot sends price=500m
From 1 command all the item prices can be viewed
Or something like that
Have you considered using a drop down?
Arguments
That will be a lot of drop down menus
async def item(ctx, *, medal):
if medal in ("gold", "golduwu"):
...
elif ...
I'd recommend dropdowns or buttons
Depending on the items in the bot
command groups
or yeah thats the first thing which came to my mind π groups would better
@bot.group()
async def item(ctx):
...
@item.command()
async def gold(ctx):
...
correct me if im wrong, Haven't used dpy for months.
!d discord.ext.commands.Group.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to
the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
ok so now how do i check if the author had a url that start with youtube.com like ?d https://www.youtube.com/
So this would work when doing a?item medal or a?item gold
Right?
!pip validators
yes!
Oooh nice
Iβll try it
Wouldnβt it be better to have all the item data in a dictionary and use arguments to get the items info?
if "https://youtube.com" in message.content:
Instead of having to create a new block of code every item
It would be shorter and easier
no, that would just be extra handling+ none of the options would show up in a dynamic help command
if message.content.startswith("https://YouTube.com"):
This still gonna take a while because the bot got 50+ items
Sadge
Or you can check if it's in the message content, no great solutions for that
Thatβs why using loops and stuff would be better
I think my bot is around there too
I use about 4 drop downs for all the ones you can buy
4 different market types split across 2 NPCs
Oh and how can I get a userβs avatar in Footer?
Avatar of the user who used the command
Regex is a solid option
what does the command do?
I think the tidiest would be using a slash command with a value that's only for a URL, depending what they're doing. Makes life so much simpler.
You can't have custom param types
For dank memer item trade prices
Any help?
Yes but once you have a value that's just for a URL you can just use the URL validator
For the entire value
how to make the bot reply to the msg
Sure but then it's just an argument
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
Anyone any experience with making a paginated help command with or without buttons (The help command is classed and it's mapping)
I've tried reading the example walkthrough but I have no idea to get started with it.
If so, mention me if you can help me in dms
Um?
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.
hi im learning C
set_author
icon_url kwarg
icon_url is smth else, if u want it in the footer it's set_author
Author icon in footer icon_url
hi why
yes
do you know what a footer is
Only set_author?
no wait, sorry.
this is an example from my code:
e.set_author(name=editsnipe_message_author[channel.id], icon_url=(editsnipe_message_author[channel.id]).avatar_url)
e.set_footer(text=member)
cuz c++ and c syntax are almost same
so embed.set_author, and in that the icon_url
you can easily remember it by the word "foot" cuz it's at the bottom, set_author gets it to the upper part
sick
why in this channel
Iβm telling that I want the avatar of the user who used the command
its exciting to learn new things
you said footer
Yea
Samandra
In the footer icon_url=ββ
yes
items = {'item1':100, 'item2':50}
@bot.command()
async def item_cmd(ctx, *, item = None):
if(item in items.keys()):
await ctx.send(items.get(item))
elif item == None:
await ctx.send("All the items...")
else:
await ctx.send(f"Item not found with alias {item}")
``` this seems much more viable
oh
well icon_url = member.avatar.url
unless you're not on 2.0
then it's member.avatar_url
right i messed up what i said, it's set_footer and then member.avatar_url
if ur not on 2.0 ofc
This
yes that
k
yea that would be Better since they have mant items, i thought it was just a few
*many
try to do py icon = member.avatar if icon is None: icon = member.default_avatar.url else: icon = icon.url embed = discord.Embed() embed.set_footer(icon_url=icon, text=member.name)
await ctx.send(items.get(item))
await ctx.send(items[item])?
its a safer way to use .get()
why
it saves you from having to handle an exception
what exception
bruv
[] returns exceptions
yes i know
.get returns None if the item doesn't exist
you said [] is safer than .get
what exception and why would it raise one?
read again
still nothing
"safer way to use .get()"
!e dict = dict()
print(dict.get(''))
print(dict[''])
@quaint epoch :x: Your eval job has completed with return code 1.
001 | None
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | KeyError: ''
i have a check and i can pick out this message
but how can i see who sent the command
[] is not safer
it's not what he said
I said .get() was safer
kek
Fuckin hell π
but I'm asking what error it would raise
KeyError
it cannot be a keyerror because he checks if item is in the keys
What π
.
if item in items.keys():
Thatβs a whole different check
!e dict = dict()
print(dict[''])
@quaint epoch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: ''
no
cya
you aren't proving anything
what is going on they already said that .get was better 
What are we arguing about here
wait what are we talking about
better but unnecessary in the case he already checked if that key is already in the dict
Suggest more topics here!
wym by that
a status option for their hosting platform
.get is not a check
no you just didn't read a message properly
is anyone able to help?
if is a check, ifs are checks
bro I'm gonna write a code
the only thing we understand
no hooman engrish, code
he gonna write a code 
interaction.user?
!e
my_dict = {"sure" : "first", "ok" : "second", "again": "working"}
if "hello" in my_dict.keys():
print(my_dict["hello"])
else:
print("There isn't a key called hello.")
if "sure" in my_dict.keys():
print(my_dict["sure"])
else:
print("There isn't a key called sure.")
@heady sluice :white_check_mark: Your eval job has completed with return code 0.
001 | There isn't a key called hello.
002 | first
what are you showing us
that you don't need .get()
ive gone over this
it's literally the only thing I wanted to show and this situation came
.get() is safer and better to use
sorry how would i use that?
thats why i used it
then you can remove the if statement
u want to see who invoked the command right?
Ty it works
this is #discord-bots for incorrect controversial garbage lets head over to #ot0-psvmβs-eternal-disapproval
cold
beef
you need to assert dominance
I got muted last time
yes, this is really the right place to assert your dominance against me
lol
If you have many items my other option would be better
and sarth agrees
.topic
Suggest more topics here!
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
i think everything should have an option to be getch-ed
roles, members, users, guilds
how can i get a cog to print when it is done being loaded?
try printing 'done' at the end of the init
how are u loading the extensions for the cog?
Roles fall under 1 << 0
bot.load_extension('cogs.developerfeatures')
chuck a print below that then
ok
@clever field spit it out tbh
Hey @clever field!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
akh
Lmao
ok
https://paste.pythondiscord.com/eqayimaluq
https://paste.pythondiscord.com/asuseviwom
Traceback (most recent call last):
File "E:\LeynBot discord.py\venv\lib\site-packages\nextcord\player.py", line 685, in run
self._do_run()
File "E:\LeynBot discord.py\venv\lib\site-packages\nextcord\player.py", line 672, in _do_run
data = self.source.read()
File "E:\LeynBot discord.py\venv\lib\site-packages\nextcord\player.py", line 625, in read
ret = self.original.read()
File "E:\LeynBot discord.py\venv\lib\site-packages\nextcord\player.py", line 289, in read
ret = self._stdout.read(OpusEncoder.FRAME_SIZE)
AttributeError: '_MissingSentinel' object has no attribute 'read'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\LeynBot discord.py\venv\lib\site-packages\nextcord\player.py", line 699, in _call_after
after_return = self.after(error)
File "E:\LeynBot discord.py\utils\func_music.py", line 237, in play_next_song
raise VoiceError(str(error))
utils.func_music.VoiceError: '_MissingSentinel' object has no attribute 'read'
I use loop, if music is over bot gave me this error
how fix that ?
We don't help with music bots, you have been made aware about this before. Please stop asking ToS breaking questions.
Yeah fuck those music bots β
Because they are allowed
..?
I would assume that mee6 has music because theyβre allowed
No they all break ToS.
K
grrr
@slash_command(name="avatar", description="changes your bot avatar", guild_ids=guild)
async def avatar(self, ctx, link):
if ctx.author.guild_permissions.administrator== False:
return await ctx.respond("No permes")
async with aiohttp.ClientSession() as session:
async with session.get(str(link)) as resp:
if resp.status != 200:
return await ctx.send('Could not download file...')
pfp = await resp.read()
await self.bot.user.edit(avatar=pfp)
await ctx.respond("Done")
``` the connection keeps closing
name 'bot' is not defined
did u define it
i think requests would be a better option
what
using aiohttp for a single request is unnecessary
aiohttp is requests in async
but did u define it?
i would still use requests, but sure
But that's blocking 
are they in other files
wait, is it trying to send a get request, or download a file?
then you more than defined it else where
download a file
Do you got an error tb?
yeah then use aiohttp
trying to change the bot avatar within a command
In both situations I'd use aiohttp.
one sec let me run it again
most discord forks are async, async is a good practice for apis, yeah it checks out
I get an error about the connection being closed
thats really it
Share the traceback please.
aiohttp.client_exceptions.ClientConnectionError: Connection closed
alr one second
gnoring exception in command avatar:
Traceback (most recent call last):
File "/home/runner/v-2/venv/lib/python3.8/site-packages/discord/commands/core.py", line 113, in wrapped
ret = await coro(arg)
File "/home/runner/v-2/venv/lib/python3.8/site-packages/discord/commands/core.py", line 762, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/runner/v-2/cogs/misc.py", line 48, in avatar
pfp = await resp.read()
File "/home/runner/v-2/venv/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 1036, in read
self._body = await self.content.read()
File "/home/runner/tester-2/venv/lib/python3.8/site-packages/aiohttp/streams.py", line 349, in read
raise self._exception
aiohttp.client_exceptions.ClientConnectionError: Connection closed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/v-2/venv/lib/python3.8/site-packages/discord/bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "/home/runner/v-2/venv/lib/python3.8/site-packages/discord/commands/core.py", line 312, in invoke
await injected(ctx)
File "/home/runner/v-2/venv/lib/python3.8/site-packages/discord/commands/core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientConnectionError: Connection closed
Ah you are reading the object outside of the context.
alr one second
Thanks
bot.get_emoji

!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
you enter the id of the emoji, returns the emoji
emoji = bot.get_emoji and then you need to call it
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
!d discord.ButtonStyle.url
use this for the style kwarg
AttributeError: 'Object' object has no attribute '_get_channel'```
anyone know what this error is?
can u show the code pls?
!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.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.
No Errors. I don't understand why this is not working. I've been trying to fix this for the past hour now
@bot.command()
async def ban(ctx, user: nextcord.User, *, reason=None):
guild = ctx.guild
if reason == None:
reason == "Not Specified"
embed1 = nextcord.Embed(title="User Successfully Banned!", description = f"**{user}** has been banned!")
embed2 = nextcord.Embed(title=f"Ban Information on {user}!", color = nextcord.Color.red())
embed2.add_field(name="User", value = f"{user.mention}")
embed2.add_field(name="Admin/Moderator", value = f"{ctx.author.mention}")
embed2.add_field(name="Reason", value = f"**{reason}**")
embed2.set_footer(text=f"User ID: {user.id}")
embed3 = nextcord.Embed(title=f"Your Ban from {guild}", description = f"You were banned from {guild} because **{reason}**", color = nextcord.Color.red())
if user.guild_permissions.manage_messages:
error1 = nextcord.Embed(title='User is an Admin/Moderator!', color=nextcord.Color.red())
await ctx.send(embed=error1)
return
else:
if ctx.author.guild_permissions.ban_members:
await ctx.send(embed=embed1)
await guild.ban(user=user)
log_channel = bot.get_channel(879095317771997246)
await log_channel.send(embed=embed2)
await user.send(embed=embed3)
user.guild_permissions.manage_messages user cant have permissions
you can't ban a user
and unnecessary if/elses
you ofcourse can
!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/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to
do this.
"user"
if :
...
return
else :
if :
... ``` π
switch user.send() and guild.ban(user=user)
you can simply shorted it to ```py
if :
return await ctx.send(embed=error1)
if :
...``` since you're already returning
AND user's not a kwarg
let me introduce you to return ...
are u on dpy 2.0?
if yes now its avatar.url
i was gonna type yes ? avatar.url : idk
still not working
Should I try member: nextcord.Member?
:)
add a kwarg in ur add_field called inline=False
embed.add_field(..., inline=False)
ya if u want all of them be like that
?
ya thats fine
yea?
which lib?
library
like discord.py
Are you synchronizing your commands for all servers or have you set up a test server?
synchronization of slash commands for all servers takes about 1 hour
how to run a bot with python?
i want to make a looking for group kinda function in a discord bot for a game. It store the ppl waiting in queue in a json file inside a list. i want to basically create a discord text/voice channel and overwrite the perms to only allow ppl who are in that list to view and access those channels if that makes any sense
i have most of the code done im just trying to figure out how to go about the perms for the users in the list
open a terminal and run python3 filename.py
you could try, but I don't expect that to do much
why does reloading my cogs not stop this from running?
@commands.command(name="count")
@commands.has_any_role("Owners β¨")
async def count(self,ctx, choice=None, confirmation=None, amount=None):
while True:
print("Attempting to update counter")
with open("totalcount.stonks","r") as f:
totalcount = int(f.read())
f.close()
with open("dailycount.stonks","r") as f:
dailycount = int(f.read())
f.close()
staffchannel = self.bot.get_channel(962825990030102568)
await staffchannel.send(f"TotalCount: {totalcount} DailyCount: {dailycount}")
totalchannel = self.bot.get_channel(968972997031506002)
dailychannel = self.bot.get_channel(969008266921259088)
await totalchannel.edit(name=f"Total Requests: {totalcount}")
await dailychannel.edit(name=f"Requests Today: {dailycount}")
print("Success")
with open("logs.stonks","r") as f:
logschannel = int(f.read())
f.close()
logschannel2 = self.bot.get_channel(logschannel)
embed=discord.Embed(color=0xFFC0CB)
embed.set_author(name=f"Member count has been updated! Total: {totalcount} Daily: {dailycount}")
embed.timestamp = datetime.datetime.utcnow()
await logschannel2.send(embed=embed)
await asyncio.sleep(660)
loaded cogs.Commands
Attempting to update counter
Success```
i want to make a looking for group kinda function in a discord bot for a game. It store the ppl waiting in queue in a json file inside a list. i want to basically create a discord text/voice channel and overwrite the perms to only allow ppl who are in that list to view and access those channels if that makes any sense
i have most of the code done im just trying to figure out how to go about the perms for the users in the list
try to change the condition while True
how would i go about that
I'm having some kind of deja-vu
!d discord.Member.guild_permissions
property guild_permissions```
Returns the memberβs guild permissions.
This only takes into consideration the guild permissions
and not most of the implied permissions or any of the
channel permission overwrites. For 100% accurate permission
calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for")...
why are you using a while loop?
He's also closing a file inside a context manager.
i want it to run every 11min
and tasks didn't work when i tried using them
from discord.ext import tasks
@tasks.loop(minutes=11.0)
async def ...():
...
doesn't work with how i have cogs set up
it won't let me change channel name, i tried this all last night
import time
...
...
while True:
...
time.sleep(660)
or asyncio.sleep
what?
Please don't send this inside #discord-bots.
it's better asyncio.sleep
π
I recommend the usage of tasks.
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with
optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
i already tried this last night
@tasks.loop(seconds = 5) # repeat after every 10 seconds
async def myLoop():
with open("count.stonks","r") as f:
count = int(f.read())
f.close()
channel = bot.get_channel(903918973408665620)
channel.send("{count}")
myLoop.start()
Unhandled exception in internal background task 'myLoop'.
Traceback (most recent call last):
File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 752, in myLoop
channel = bot.get_channel(903918973408665620)
NameError: name 'bot' is not defined
``` it doesn't work for some reason
are you using cogs.commands?
from discord.ext import commands
import asyncio
import logging
import datetime
import os
import re
import random
import json
import requests
from random import choice
import time
from discord.ext import tasks
client = discord.Client()
class Commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="partner")
@commands.cooldown(1, 21600, commands.BucketType.user)
async def partner(self,ctx,member: discord.Member=None):
-----
def setup(bot):
bot.add_cog(Commands(bot))
this is the setup i've been using so far inside a cog
I use Client 
i subclass clientπ³
from discord import Client
class OkimiiClient(Client):
...
π³
Same
They added the bot slash command management to Discord 
hi, i want to create a dashboard for my bot with python with mongodb what is the best way to do that?
yes
You can access it from a website or a bot it doesn't matter.
If you want to create your own dashboard you will need to look into making your own API or IPC.
I recommend an API since it's better if you want to host your site somewhere else.
i heard that there are libs for making dashboards such as flask or quart
yeah i want to host my own site
For IPC based structures yes.
But that's more if you want a private dashboard.
are the new bot integrations working or do they just take a long time to update?
still hasn't restricted them
@client.command(name="setup")
async def setup(ctx):
await ctx.send("Starting setup! What does the name of invite channel needs to be?")
member = ctx.author
def check(m):
return m.content != "" and m.channel == ctx.channel
msg.author == member
msg = await client.wait_for("message", m.author == member)
await ctx.send(f"Channel named {msg.content} made")
``` How do I define `m` here?
is it the check=check?
m will then automatically be the parameter of the event gathered, in your case a discord.Message object
Yep
But where?
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
Yeah I tried before but didn't understand it
You have an example
msg = await client.wait_for("message", check=check)
I already knew that still says that m is not defined
should that be msg?
And that will never change
slash command is saying "missing 1 required positional argument" but i marked it as unrequired
check=your_function
Considering your function's name is check then it's simply check=check
Just like in the documentation
No.
m is automatically defined when you pass your function in the check kwarg as I've already said above.
Forget about m
I mean my error is the m.author
Just know it will represent the parameter of the event fired, in your case a message
Because you don't listen...
Maybe because I don't get your explanation?
msg = await client.wait_for("message", m.author == member, check=check)
``` got this atm.
its kinda basic python no?
The kwarg is check and that will never change as I've said above
it doesnt take 2 positional arguments.
So remove m.author==member
1 only positional and 2 only kw
As m.author is not a kwarg for this method
Yeah okay now I finally get it
Just look at the documentation again - the example is self explaining
am i missing something with the integrations page
slash commands still accessible from every channel
Oh that's cool. Didn't know that was a feature
just notified of it today
think it's only just rolled out to everyone
- although so far it doesn't seem to be working, at least for me
intents = discord.Intents.default()
client = commands.Bot(command_prefix = '$' , case_insensitive = True , intents = intents)
@client.event
async def on_member_join(member):
wlc_channel = client.get_channel(968900428702031885)
await wlc_channel.send(f"{member} has joined the server!")```
someone tell me why it doesnt work
(welcome message)
Does your bot have member intents?
Any errors?
no
Any error handlers?
it just doesn't send welcome message when someone joins
on_error or on_command_error anywhere at all in your code?
And yes, check your member intents
need some helps here, when someone does a command example !daykey, it sends a message to a certain webhook
!pip requests
How do i create a forum channel?
A thread?
Whatβs that supposed to mean
Thread only channel
really isnt needed
The wrapper?
dpy
don't use discord.py's http client
what else do you think im talking aboutπΏ
need some helps here, when someone does a command example !daykey, it sends a message to a certain webhook
why? and you can still use the internal session
unless you wanna expose your bots token to every site you make a request to"
nope, don't use that also
why
The internal client session sends your token to sites it makes requests to
!webhook
So you don't want to use that; it's private for a reason
does it have a default header?
@slate swan can you help me?
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`...
not exactly sure how the headers are set but you should handle your own session regardless
ill check src later

lol

Only select servers have it accessible right now
they're kind of rolling it out slowly
this server actually has one, it's just internal and we're testing it
my server has access to them
ah, maybe they fully rolled it out?
i got a little message thing today telling me my server has them
i went to make a new channel, not there
was I pinged here?
here its correct but i still dont know why you wouldnt use the aiohttp internal client session
anyone?
I already said why, it isn't hard to handle your own as well
It's private (and mangled) so you don't use it
why would you start your own tho?
im watching a tutorial on how to make a discord bot
and im trying to navigate to the file
make sure the path is correct
wym
In this video, we will learn how to setup a discord bot in python using discord.py v1.4.1 (rewrite) in 2020
UPDATED VERSION: https://youtu.be/T5moR5gBlbM
If you have any suggestions for future videos, leave it in the comments below.
Some Useful Links -
Python: https://python.org
Sublime Text: https://www.sublimetext.com/
My Discord Server-...
wheres desktop in your pc?
hm
what could be causing this error?py Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\bot\main.py", line 23, in <module> bot = Zupie( File "C:\Users\Teagan\Documents\Coding\Zupie\bot\classes\zupie.py", line 29, in __init__ self.config = Config() AttributeError: can't set attribute 'config' ```py
from .configenv import Config # I think that import statement is right, the configenv is in the same dir as the file with the Zupie class
class Zupie(commands.AutoShardedBot):
def init(self, **kwargs):
super().init(**kwargs)
self.config = Config()
self.redis```
is that what you where looking for
yes
cd OneDrive > cd Desktop > cd $ad bot
alr that worked one sec lemme try to load it
i did that but it didnt send "bot loaded"
@cleint.event
async def on_ready():
print("Bot is ready")
How to make a condition that if a user is not a server admin then ...
show bot.py
what is?
whts the default delete_message_days value for member.ban ?
1 day
thanks
again, show your code.
tutorials are not an reliable way to learn discord.py
im starting to realise
from http import client
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='.')
@bot.event()
async def hello(ctx):
await ctx.send("Hello")
``` thats all i got rn
you're not running the actual bot.
im not sending my key thing
bot.run(token)
or
bot.start(token)```
i would disagree on that statement.
let me rephrase, tutorials for third party libraries such as discord.py are not an reliable way to learn
tutorials can be good but most for third party libraries get old fast
Your point is quite general in a sense of saying all tutorials are bad, i feel like its a very strong statement that isnt correct.
Any gist or example on how to get a part of string
e.g
Amazing job, we racked up a sum total of {amount} from {user}
Where amount and user keeps changing and the other part remains same(Which will be used to trigger)
The majority are.
Try recommending more than 2 good tutorials
You are quite missing my point, i will not answer such a question that will not prove anything.
Exactly.
Exactly, you have no point to prove.
Yet you can't share the tutorials
I agree with @final iron.
Whats your point? Do you even have one?
My point is basically all the tutorials suck
I would disagree.
Okay so share more than 2 that don't suck
Whats your point?
...
- documentation has examples.
- github repo has a whole example folder
- many good developers have made tutorials that are still being maintained
Your point is quite wrong.
Hello
hi
Okay so share more than 2 tutorials that are good
I already have.
Documentation doesn't really count as a tutorial on this context
And neither does the repo
See, you have no point, you barely can prove your own statements.
Wut
He did just prove them.
Documentation is definitely not a tutorial
It's a reference, not a tutorial
And the repo is exactly what you said it was for. Examples. Not a step by step guide
Which increases copy/pasting, Therefore the person doesn't actually learn anything
Out of the thousands of tutorials that exist I'm only aware of 1 that is good
This counts as a good tutorial?
on_message for commands?
Also it's very brief
Its being changed in main already, so my point still stands.
But it's not currently changed isn't it?
So that source doesn't matter for someone starting now
Whats your point?
.
And we've already gone through why the repo doesn't count as a tutorial
You want a good beginner tutorial when discord.py is an advance lib you do know theres not much tutorials as the documentation is quite straight forward to the targeted crowd.
How does it not.
This
This
.
Its quite the same purpose. It guides you to success.
So were left with vcokltfre
But it's not a step by step tutorial
And that's what most people are looking for when they start
Its quite funny as your missing all my statements and saying nonsense.
You and I both are fully aware most people don't have a lot of knowledge of python as a whole before starting with discord.py
Which statements am I missing?
As said.
Right here
Theres quite allot of flags in the documentation so its quite not the developers fault but theres.
Never said it's the developers fault but it's what happens in the real world
So were still looking at 1 tutorial
Nonsense.
We've already gone over why the documentation and repo are not tutorials
You have been given many tutorials, but deny all of them, what do you expect of them to give a step by step of everything, every single endpoint?
Yeah, no.
A step by step explanation is what most people look for
That's why they look for tutorials
In an advance library?
That's the whole point of tutorials. Everything should be explained
Correct.
You and I both are fully aware most people don't have a lot of knowledge of python as a whole before starting with discord.py
Its quite easy to read documentation dont you think?
so true
All that would help a beginner is the FAQ
Which is not a tutorial
Its an advance library bro.
.
You keep ignoring that most people who use discord.py are beginners
if you don't wanna help them then just don't answer
Your point is quite not strong, Its like saying theres a tutorial for everything advance, i.e a whole tutorial on how to be a doctor when its such a huge topic and such an advanced one, so your point is quite not right.
discord.py isn't even close to being as hard as a doctor
You missed my whole point.
^
ok on a real question note, error handler for MissingRequiredArgument?
Yeah and?
Each patient is different when you're a doctor
Like majorly different
"just code"
Well yeah
And you expect a tutorial for all of them?
You have proven my point.
You can't compare a tutorial for a doctor to a tutorial for discord.py
No?
can you guys argue somewhere else π€£
It fits the topic here.
I will not continue this conversation as you just proved my own point.
Sounds like somebody ran out of points π€£
No
good idea
Well, it was before they went to doctors for some reason
And you expect for a dpy tutorial to show everything?
is anyone gonna actually help with discord.py π€£
No but it can show how to create commands
Whats the issue?
I can try.
For each endpoint?
how can I make a error handler for MissingRequiredArgument.
No, but the basic ones
you can use a try and except or a custom error handler for a command
Read this https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612, it has examples on how to handle that error and other errors
I thought a try wouldn't work for this type of error?
Theres already in the documentation so youre still proving my own point.
It would
The documentation isn't a step by step tutorial
We've gone over this
@play.error
async def on_command_error(error, ctx):
if isinstance(error, MissingRequiredArgument):
await ctx.send("You did not give me anything to repeat!")
like this?
Its your standard, if you dont understand it then thats your problem.
yeah but check it with isinstance
It's almost every beginners standard
"It's almost every beginners standard" in an advance library?
When you know nothing about something you need it explained step by step
Sure, but this'll send a message on every error, and it'll also eat up errors
You and I both are fully aware most people don't have a lot of knowledge of python as a whole before starting with discord.py
Ran out of points?
No
edited it, is that better?
You're just ignoring that one
Yes, and also add an else statement so that it doesn't eat up errors
Because going back to your own points that have been proven is quite a waste of my time.
great.
You're doing the exact same thing?
You've said it's an advanced library for the 3rd time now I think
And that's your whole reasoning why beginners don't use discord.py
You already have proved my point and i have proved my own, i will not continue as your "standards" are so high for such an advance library as discord.py.
its an advance library that uses oop bro
what would be a good one liner for this so it excludes j[1] and j[3] when i append a tuple
Yeah and?
Bro
You think that matters to beginners?
No point.
i ment you have no point.
@boreal ravine what if the command is in a cog? how would I do it
You have no point to prove, because you already have proved my own.
add self to the parameters
So you're saying beginners at python don't use discord.py?
^
and the error handler code would go within my cog or in main file?
either
My point is beginners at python don't care if discord.py is an advanced library
They're going to try to use it either way
@final iron @slate swan why don't we stop right here, this conversation isn't going anywhere and is rather heated
Thats not his point again.
I will stop, as this conversation isnt going anywhere and is quite a waste of my time.
For some reason i'm getting
Command raised an exception: NameError: name 'MissingRequiredArgument' is not defined
Bye!

Code?
@play.error
async def on_command_error(self, error, ctx):
if isinstance(error, MissingRequiredArgument):
await ctx.send("You did not give me anything to repeat!")
Well did you imported the class?
well it's in my cog.
Still you would need to import the class from the discord module
this is the solution i decided to go with, idk if it could be better, probably
using?
pardon?
is it just the
from discord.ext.commands import MissingRequiredArgument
?
from discord import MissingRequiredArgument
not sure if thats the right namespace tho im not sure if it was imported in the init file of the module
so this wouldn't work
!d discord.ext.commands.MissingRequiredArgument
nope
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter
that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
It will
Lmfao
Nah it's somehow in commands
lol
somehow?
for some reason it's not sending the message.
Why would it not be? Itβs an error that only applies to the commands framework.
Those are base exceptions like HTTPException, Forbidden, NotFound, etc
yeah it makes more sense
and hey tylerπ

hm I don't know why it's not sending the message
can you show code?
@play.error
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("You did not give me anything to repeat!")
why is it named on_command_error?
oh it works now
lol
before I had error, ctx
and change the functions name
Careful with that
If you don't have an else: to catch all other errors it's going to eat them up
Anyone here that can help me with my file to make it into 2.0? I've been at this for like an 1h+ and I've asked other people for tips and I can't seem to figure it out. All I need is someone to help me or to setup my file correctly, I can do the rest from there
can you elaborate?
With your current code, all errors that aren't commands.MissingRequiredArgument are going to be ignored
and what would go in the else: ?
re-raising would be easiest
probably just send the error or raise it
if isinstance(...):
...
else:
raise error
oh I see. thanks for the information
you're missing a required argumentπ
hm?
in the isinstance ik its just pseudo code but its triggering meπ
Β―_(γ)_/Β―
π
Anyone?
What do you mean, make your file into 2.0?
maybe rewrite from 1.7.3 to 2.0?
how do i make the bot print the name of the person who join the server?
you can use the on_member_join event, it takes a single argument "member" which would be a discord.Member, you can simply print(member) to get member#1234 or simply print(member.name) for just the name
@bot.event
async def on_member_join(member):
print(member)```