#discord-bots
1 messages · Page 740 of 1
and you can't make commands like that, see https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html and https://tutorial.vcokltfre.dev/
How to make this loop
got this while searching up on google
^ @unique tendon
noice
@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
if member == ctx.author:
em = discord.Embed(
description=f"**you** cannot `mute` yourself", colour=discord.Colour.red()
)
await ctx.send(embed=em)
else:
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
x = get_role(883538063496708116)
x1 = get_role(883705723572342855)
x2 = get_role(910023978607857684)
x3 = get_role(888220698680647710)
x4 = get_role(888253795535056926)
x5 = get_role(811491773188800552)
x6 = get_role(811491879853621260)
await member.remove_roles(x, x1, x2, x3, x4, x5, x6)
em1 = discord.Embed(
description=f"{member.mention} has been `muted` for **{reason}**",
colour=discord.Colour.green(),
)
em2 = discord.Embed(
description=f"**you** have been `muted` for **{reason}**", colour=0
)
await ctx.send(embed=em1)
await member.send(embed=em2)
list_of_muted_members.append(member)
print(list_of_muted_members)```
its not sending the embed nor give the muted role when i use the command.
free hosting service with replit: uptime robot + a simple code to type in replit.
thats not a bot hosting service
it hosts the bot 24/7
the bot restarts at every 30minutes-1 hrs , rip cache
no, i do it and it's perfectly fine
- It never adds the muted role since you never used
add_roles - It's not just
get_role, you need to use it on aGuildobject, example:ctx.guild
arguable topic , but replit is bad for hosting anyways
its an ide , not a host
Both are equally bad.
imo not really, i mean replit has its own bad qualities but its definitely a better service than heroku.
Can anyone pls help me with buttons i still don't know how to add them
What library are you using?

using commands.Greedy, if a member isnt found how do i get it to raise MemberNotFound
for some reason when i didnt specify a valid member it'll still work
you can use a try except block
Where in the except, you specifically look for the MemberNotFound
or you can use the raise keyword
Heroku is made for web services
Is there a way I can make the bot find the message_id of the message the author replied to?
For example, A replies to B's message with the bot's command in the message's content. Now, how do I find the message ID of B's message (which A replied to)?
message.reference
Returns an object of this type
!d discord.MessageReference
class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)```
Represents a reference to a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.5.
Changed in version 1.6: This class can now be constructed by users.
How do I implement it?
Use .reference on the message object.
As I said, it returns an object of this type
Ohh, so it just returns a message object.
Then you have multiple attributes to use.
No it doesn't
discord.Message != discord.MessageReference
I see.
Click on it and you will see yourself.
Mkay
Ok new issue, how do I convert a message id back to a message object.
@slate swan Can you help?
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
I see.
no errors raise
because of how the converter works i think
thats why even when member is not found it doesnt raise the error for me
Could you show your code?
no CommandInvokeError?
msgId = ctx.message.reference.id
msg = await discord.fetch_message(msgId)
await msg.reply(content)
Is this correct?
Seems valid but msgId is not following naming conventions
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
Hmm, lemme change it ig
s n e k
"most input errors are silently discarded"
@heavy folio could you show how you typehint your args in command?
async def _command(self, ctx, member: commands.Greedy[discord.Member]):
...
Um
wait
And where is the argument you typehint lol? Typo?
i did i said its a typo
This isn't working, can someone help me?
I am trying to find the message which the author replied to (with the command in the content), and I want the bot to reply to it too)
I mean if there's anything following Greedy argument with default value, it might prevent it from raising error like
async def command(..., member: Greedy[Member], num: int = 0)```
nope i dont have snything after that
No.
Rip
You need to use it on a discord.TextChannel object.
Is your argument typehinted with Greedy the last one?
I see.
wdym
Which you eventually don't have, so you need to use channel = bot.get_channel(id) and then use on that variable the fetch_message method.
Do any arguments go after the one typehinted with Greedy?
Ok thanks
And as I said, click the link to know more about MessageReference since it's not a Message object and therefore doesn't have a id attribute.
nope
I guess it's possible to avoid typehinting it with greedy, you could just use list of arguments
async def cmd(ctx, member: discord.Member, *roles: discord.Role)```
@heavy folio
Mkay
Greedy is needed when you want to like insert the list of arguments inside
If it goes for last just use list of arguments
You can try, message.reference.cached_message.id to directly get the ID of the message, but if the message is not cached, it won't work.
What does cached mean again?
in memory
Ok thanks
oh
alr thanks
Why can't you just use MessageReference.message_id?
Hm?
could someone indent/unindent this for me?
@bot.command(pass_context = True)
@commands.has_permissions(manage_messages=True)
async def unmute(ctx, member: discord.Member, reason=None):
mutedRole = discord.utils.get(ctx.guild.roles, name="☁️ | muted")
embed=discord.Embed(description=f"{member.mention} has been `unmuted` for **{reason}**", colour=discord.Colour.green())
em1=discord.Embed(description=f"**{member.mention}**, you have been `unmuted` for **{reason}**", colour=0)
await ctx.send(embed=embed)
await member.remove_roles(mutedRole)
await member.send(embed=em1)
else:
if member == ctx.author:
em2=discord.Embed(description=f"**you** cannot `unmute` yourself", colour=discord.Colour.red())
await ctx.send(embed=em2)```
Why can't you do it by yourself?
!indents Will help you
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
Also why is there else coming out from nowhere
And do you know that theirs a new feature for doing that mute, unmute
member.timeout(...)
# or
member.timeout_for(...)
Because she's using old library ig
she's*
It is only available in forks
thank you
Kk sorry
no worries
thank uuu!
hmm
Error: name 'bot' is not defined
Hey @sullen pewter!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey @sullen pewter!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
@bot.command(name='hack')
async def hacker_man(ctx, member: discord.Member):
ran_sleep = random.uniform(1.75, 2.25)
email, password = login_generator(member.display_name)
friends = random.randint(0, 1)
_dm = random_dm()
common_word = random_common_word()
member_disc = str(member.discriminator)
random_port = random.randint(1123, 8686)
random_subnet = random.choice(('192.168.0.', '192.168.1.', '192.168.2.'))
random_ip = random.randint(0, 254)
msg = await ctx.send(f'Hacking {member.display_name} now...')
await asyncio.sleep(ran_sleep)
await msg.edit('Finding discord login...(2fa bypassed)')
await asyncio.sleep(ran_sleep)
await msg.edit(f'Found login info...\n**Email**: {email}\n**Password**: {password}')
await asyncio.sleep(ran_sleep)
await msg.edit(f'Fetching DMs with closest friends (if there are any friends at all)...')
await asyncio.sleep(ran_sleep)
if friends == 0:
await msg.edit(f'No DMs found.')
else:
Hey @sullen pewter!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
await msg.edit(f'DMs found...\nLast DM: "{_dm}"')
await asyncio.sleep(ran_sleep)
await msg.edit('Finding most common word...')
await asyncio.sleep(ran_sleep)
await msg.edit(f'Most common word = "{common_word}"')
await asyncio.sleep(ran_sleep)
await msg.edit(f'Injecting trojan virus into member discriminator: #{member_disc}')
await asyncio.sleep(ran_sleep)
await msg.edit('Setting up Epic Store account...')
await asyncio.sleep(ran_sleep)
await msg.edit('Hacking Epic Store account...')
await asyncio.sleep(ran_sleep)
await msg.edit('Finding IP address')
await asyncio.sleep(ran_sleep)
await msg.edit(f'IP Address Found!\nIP address: {random_subnet}{random_ip}:{random_port}')
await asyncio.sleep(ran_sleep)
await msg.edit('Reporting account to Discord for breaking TOS...')
await asyncio.sleep(ran_sleep)
await msg.edit('Hacking medical records...')
await asyncio.sleep(ran_sleep)
await msg.edit('Selling member's data to the Governement...')
await asyncio.sleep(ran_sleep)
await msg.edit(f'Finished hacking {member.display_name}!')
await ctx.send('The totally real and dangerous hack is complete.')
yes
Is this in a cog?
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.
k
Put it in there
You called your bot constructor client
So either change that or change the command decorator
There is also a spelling mistake on your cleint.run("") line
Also just an outside tip: you could put all those different messages inside a list and iterate through it to shorten your code.
the @bot.command?
what should I change it for?
@client.command
can I send 2 embed in 1 message ? in webhook I can
Why don't you try it?
I tried and can't
so im here to ask
I send embed as an array
I never would have imagined in my entire life that I would ever use replit
Turns out I need to use it to host my bot.. heroku is just shit I couldn't keep using it
use epik host
I used flask
altho all of them are just bad. not sure about epik host
Isn't there an embeds option?
message.send has an embeds kwarg iirc?
Yes u can
Starting dpy 2.0 iirc
can someone help me install UI path?
UI?
yes
It's called a package or smth not path lol
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
okay but how can i install it?
@solar anchor you want dpy 2.0?
what?
What's your dpy version
i just use python
!d discord.version
discord.__version__```
A string representation of the version. e.g. `'1.0.0rc1'`. This is based off of [**PEP 440**](https://www.python.org/dev/peps/pep-0440).
@solar anchor you know how to install packages right?
ppl give me the thing to type yes
It's pip install -U git+https://github.com/Rapptz/discord.py if you want dpy 2.0 that has support of buttons
i did that but it didnt work
Tho you'd better use fork like disnake
Where did you put that and what error did you receive
terminal and
Cmd?
ye
Ok that's alright, did you get any errors?
never heard of ui
ui is subpackage
from discord.ext
You should use
from discord.ui import ... something```
isnt it discord.ui?
i see
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.
^^
like this?
how do i do it with menus?
ill read it
я один русский?)..
thanks for help already tho
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
Нет
ура
Take a look at the examples here @solar anchor
@vale wing@slate swan, it's an English only server
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
We will go to dms dw
sorry pls(
Don't worry, just saying ^^
okay
whats menus.MenuPage?
why are you inheriting it then lmao
where did you copy it from?
In the code
it should be a built in function
it isnt
It's not
then it should be a package
@solar anchor if you are browsing source code from github on pc you can just click it and look for definition
i copied it a some days ago
From here?
no
Check out that
its not inheriting it
examples/views/dropdown.py line 9
class Dropdown(discord.ui.Select):```
examples/views/dropdown.py line 32
class DropdownView(discord.ui.View):```
thnx
Python bot has very nice functions
yeah
discord.ext.menus does exist.
You just need to install it
python -m pip install -U git+https://github.com/Rapptz/discord-ext-menus
Then you can use
from discord.ext import menus
does anyone have a code i could use for an “embed” command where the bot repeats what i said but in an embed
Have you tried to make something by yourself?
Or atleast help pls
Idk much about coding just need help making a simple bot for my server
You should learn some, nobody here will make full code for you
ok ig
!d discord.Embed , you'd be using this
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
I can recommend you some tutorials if you would like to
when a custom check like
def something:
def predicate(ctx):
#code
return commands.check(predicate)
when the above fails, what's the error to handle?
is it commands.CheckFailure
oh i thought it raised commands.MissingPermissions i see thank you
bruh if i try removing it it destroys everything
If you use discord.py, remove nextcord.
If you use nextcord, remove discord.py
So there’s one thing I don’t understand
ok
Sharding is a method to split portions of bots into separate processes. This is an enforced strategy by Discord once a bot reaches a certain number of guilds (2500). Once this number is reached, a bot must be sharded in a way that only 2500 guilds maximum may be allocated per shard.
Thank you.
..
this might not be the best place to ask, but I'm making this bot thats using sqlite3. It's gonna be used to hold money, but just for some game I play. How can I make a thing to track its usage history?
I don't think I understand the question. Are using discord's api to make this bot?
yee its a discord bot
Ask me questions
By usage history you mean the transaction history i assume.
yus
Is it a discord-based game or..
Well just create a new table for that, use the user id to join it.
wouldn't I need to create new rows for every transaction?
or could I join them into one row
No you'd want to do that automatically after every transaction.
how would I join with the user id o.o;
Maby some kind of dynamic function to log it to that table.
Personally I would make a function that would operate with user's currency and log the transaction at the same time
Best is to also make a transaction type to know what is what.
That would take way too much effort.
Not really
this sounds kind of complicated o.o
Yeah since you are creating duplicated code a lot.
I'm already somewhat familiar with sqlite3, but I don't know that much
SQL code?
sqlite3
I'd say something like
# code
Or something similar to that for the function
So like you would also need to give type to the column to identify what kind of transaction it is.
1 query to update user data and 1 to log transaction? Too much effort? Maybe you mean something else?
Yeah just create a function for it.
Eliminate repetitive code.
Didn't I say that at first lol
I mean maybe it's possible to combinate them into one query
Likely but that would get way too messy.
I don't see why that's necessary
I'd say just call the function with the user id and transaction amount
well just make some methods that store/update/remove/return user currency then you can use the freely anywhere. i dont suggest doing that on every command since it will make ur code look junky
Ofc I wouldn't
More like ```py
async def log_transaction(...):
Bruh what I suggested was combinate 2 actions into function and you are doing all this...
better discord user 
@weary mirage you should probably ask in #databases maybe they suggest better option involving sqlite's tools
oh aight
Well, in the context that they want to implement it into a discord bot
I have my own wrapper for SQL based syntax anyways so i'd only really have to add one function to log everything.
@weary mirage I think you could just create a trigger most likely it's what you need https://www.sqlite.org/lang_createtrigger.html
alright, thank you
Hey, can someone help me fetch the guild_id from a custom function??
my function gets called on_ready
don't do API calls in on_ready
I've not seen any code, no idea what you're trying to do
(await ctx.guild.fetch_member(member_id)).mention``` would mention the member, right?
which guild_id?
my on_ready func looks like this, it says in every server it's in that it's logged in and it sends every member a verification code.
but i commented out bc im the nerdy annnoying kid in school that like pushups too much and pinging everyone isn't very good and everyone hates me for it
so yeah
uh, this tells everything you need to know
i, imported too many things
wtf you have 200+ imports or what
tbh pretty much useless, what was the idea behind this
idk, i was thinking the same thing
that's why i commented it out
hm
to check if a user is a spam bot or smth i guess
i removed the commented out code
but there's still a command to manually send a code to a member
to check if they're a bot
spam bot
ig
wow i really don't know why i made this
this is just gathering dust
Do i send it as an array? Like [embed1,embed2]
this every time the bot starts ?
How would I see how many members my bot is watching over in total?
in every server it's in?
first of all you need the members intent
Yeah I got it
members = 0
for server in bot.guilds:
members += server.member_count
idk if that works
its just len(self.bot.users)
bot.users returns a list of member objects
Or something
that's pretty much wrong though
whats wrong
you loop through the server and add all the members from the server to a variable
lemme try it myself
it worked
it worked perfectly
what do you mean?
!d discord.abc.Messageable.send has an embeds kwarg
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
curious, what does the abc mean?
Abstract class
I don't think I've ever seen it being used in other libraries's docs
It just indicates that u shouldn't use these classes in your code and they are only meant for documentary purposes
Like every class which has a send method sunglasses the abc.Messageable class
Not "main"
you can do that just by lenning the guild.members
yes
well i dunno the word
lmao
base classes
the total amount of people IN ALL of the servers the bot is in
that needs member intents
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
member_count doesnt
@slate swan
i specified above that you need it
Wait member_count doesn't need members intent?
nope
!d discord.Guild.member_count
property member_count: int```
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/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
It needs
ow
Lol
nvm then
Anyways I'mma just get some sleep since my arm is already sore since morning thanks to the vaccination

first or second?
oh yeah this is going get ot
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Hello everyone,
Can someone help me ? I want all channel from a specific category, it's possible ?
hello guys, anybody help me? My problem is so dumb. I try make buttons, but it not in 1 line
how can i send a pillow object?
What do you mean?
Which library are you using?
Traceback (most recent call last):
File "C:\Users\unitt\Downloads\4214141241421.py", line 1, in <module>
from discord.ext import commands
ModuleNotFoundError: No module named 'discord'
[Finished in 0.1s with exit code 1]
anyone know this traceback? never gotten it before
Are you using a virtual environment?
Also verify your interpreter is correct
try pip uninstall discord
and then pip install discord.py
idk for me it worked when it happened
anybody?
no im not
alright ima try that
pip install discord
and if it doesn't work try to install the developement version
is there a new version of python?
git clone https://github.com/Rapptz/discord.py
cd discord.py
python3 -m pip install -U .[voice]
3.10 is the lastest
@plain shadow The command here is called !docs
do context menu commands work for mobile users?
this......isnt the right channel?
oh just noticed that my bad gang
nobody?
Can anyone say me how to make a discord bot online whit python?
how are you creating the buttons?
you learn how to-
btw, docs
where
what
huh?
I want put a bot online
how
and with Python
just help me to do that
@upbeat otter
no comment
...
cant even understand your question properly welp
my virtual environment is set, obviously i have discord.py updated, i updated everything and im still having this problem
Well that's good that you got this error since you shouldn't use requests
Run pip install requests in console
No.
i have a question
The module requests should never be used.
Use the following to make web requests:
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-web-request
i am using that only
Then you need to stop.
but it doesn't show any error till now
If you don't use the correct way to make web requests don't make others to the same mistakes.
ask
what modules do you use then?
...
if you don't mind me asking
a non-blocking one like aiohttp
It blocks your bot from doing anything until the request is done, which can drastically slow your bot.
oh
aiohttp
ok so to mention a member its member.mention because its a attr but in the source code its a function how does it work do since a function needs to be called with () and if i call it without it, it will just print the memory location
not time
not sure lol, someone more knowledgeable might be able to answer
Yep
!e
import time
print(time.time())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1641837109.4104993
Uhm so all my commands stopped working does anyone know a possible reason
oh thats a time module i thought it was used for something else🏃
The on_message event
See this ^
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the member."""
if self.nick:
return f"<@!{self._user.id}>"
return f"<@{self._user.id}>"
thats how you mention a member but its a function how so its done .mention and not .mention() since its a function?
Does one method run better than the other or is there no difference
@property does the magic
No difference
ah ic thank you
i mostly just use .listen() on all my events lol
Hey! I am trying to make a bot and i need to a ban/kick functionality to my bot
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
!d discord.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
the coros ^
if message.content.startswith("$kick"):
async def kick(ctx, member : discord.Member, *, reason= None):
await member.kick(reason = None)
Ik this is too wrong but is there any way that i could modify this
modify it by how?
and yes thats wrong
use the command handler
not on_message events
and your spaces are really off
Alright..@client.command right?
Oh nice!
❤️
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
this ^
I don't think so
may i see your code?
I'm currently too noob at this
ic
should I send you my repo?
Yes
sent!
...
@indigo karma
basic py tutorial -> https://www.pythondiscord.com/resources/
discord.py tutorial -> https://vcokltfre.dev/
object oriented programming tutorial -> https://www.programiz.com/python-programming/object-oriented-programming
yep
tut tut
not good
!d discord.ext.commands.Bot || exists for a reason
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
yeah ik😕
ive answered you already
use commands.Bot
oh uh well I
alrighty...i'll give it a try
put the if statement in the function btw
Okimii
thats me
Will it be said if I need out in one of the ot channels
everywhere I go , I see disnake
Everywhere I go
I see ||python||
disnake will be king
Let Disnake take over
Disnake rules the world now
We must hail disnake
yes
I like the fact that you type fast
Unlike the others who type at 10 WPM
I send them something they reply after 10 fucking minutes
And all they say is “hi”
My top is 84 but that was set 2 years ago
mwahahhahaha I’m now unstoppable
I can do 90 ez , never tested recently
Typing games got me through a lot of boring classes lmaoo
Me neither
I bet I can get 100
What do you use
👀
easily can do 11 sometimes
Impressive :3
😉
Idk how to properly type and the fastest I've done is 135 lol. I use one finger on my right hand and 4 on my left
Horrible at texting tho 💀
uh
use a for loop through the list of bans and unban them

lol
I love cats
I'm making a website dedicated to cats ❤️
ignore doge-net
my computer is broken
idk why
async for member in bans():
await member.unban()
would that work ?
okimii have you downloaded splitgate yet
probably not
😠
no
do it
ok
almost got banned from the dpy server cuz i mentioned disnake
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
i mean, they have a clear rule about not mentioning any forks in their server, why u so surprised
the guy was asking for a fork? lmao
you should've dmed the name then
their rules idk
is someone using Hata from here or disnake/pycord for an honest opinion
Can you make more commands as trigger for one action?
i mostly use disnake
Like "!test1" and "!test2" will output "test"
So if I say !test1 it will say test and if I say !test2 it will also say test
Without creating 2 separated commands
just use on msg and wait for those 2 msgs
if message.content.startswith("!test1" or "!test2"):
...
Oh ok
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Does anyone know a good artificial intelligence API
related to?
hmmm
Ig you can use aliases here If you want exactly the same output but just a different name of the command
thats good aswell lol
@bot.command(aliases=["test2"])
dont know why that wasnt my first option
this just gives me a syntax error. what am i doing wrong? ```py
r = requests.post(config["sync_check_url"], data = data)
except requests.ConnectionError:
await ctx.send("@round robin,@wet relic, Auth server is down. Please try again later.")```
request isnt async btw
is that why it cant work?
how do i make it not async when still doing the same thing
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
use aiohttp
i need it to wait for the response from the website
does it always wait anyway before it continues if its not async
have you read what was in the embed?
tl;dr when you do a request with the request lib the bot will not do anything until the request is done since its a sync lib you will need a async web request lib like aiohttp
is there a way to get around that
by using functions that arent async
so i can still use the requests module
nope
would it make the function async
aiohttp is very similiar
ok
!pypi aiohttp
ill take a look at it
does the python script have to be running for the bot to work?
is there a way to have it run continuously?
u can run it on a vps
if you dont run the file which runs the bot it wont do anything
then its not on ur pc but its on another computer somewhere else
you can self host or use a vps
a server
but you need to buy the server space, discord won't provide it?
well basicly same thing
i mean but a server is a big computer with different tasks
for a simple discord.py bot u shouldnt need more then 200mb of ram and u can get those pretty cheap still
i recomend sparked host for discord bots
they have decent prices
or pebble host also does discord bots i think
digital ocean is good
do they do bot hosting
it gives you 1gb of ram iirc for 5usd a month
thats not that good
very overkill
it is lmao
their ddos protection isnt great but u probably wont be using it as a public vps
welp thats the downside of it
still not very good of a option
i didnt notice anything untill they emailed me lol
they probably wont be running the bot on a vps they will be sharing with
so its probably fine to get it for their use case
i have this:
while t != timer:
try:
guess = await client.wait_for('message', check=is_correct, timeout=timer)
except asyncio.TimeoutError:
await ctx.send('Time has ran out!')
if guess.content == answer:
await ctx.send('Well done! You are correct!')
break
elif guess.content != answer:
await ctx.send('Your punctuation or spelling was incorrect. Try again!')
but it only looks for a message once and not repeatedly
Guys, what extension do you use to make discord bot in Python?
nextcord, pycord, dissnake
any work
i dont recomend discord.py anymore because its not supported
uh...what does it do?
you can still use it
nothing from stopping you
but yeah it is unsupported
I'd go with disnake.
all i said was it wasnt recomended
didnt say u couldnt use it
basically its supposed to check if a message is the same as a string during like a 5sec period of time
but what happens instead
this is the command
@client.command(aliases=['tr'])
@commands.has_role('Owner')
async def typeracer(ctx):
timer = random.randint(4,7)
answer = 'A test sentence!'
userid = ctx.author.id
t=0
def is_correct(ctx):
return ctx.author.id == userid
send = '``'
send+= answer
send += '``'
await ctx.send(f'You have {timer} seconds')
await ctx.send(f'Type this sentence:\n{send}')
while t != timer:
try:
guess = await client.wait_for('message', check=is_correct, timeout=timer)
except asyncio.TimeoutError:
await ctx.send('Time has ran out!')
if guess.content == answer:
await ctx.send('Well done! You are correct!')
break
elif guess.content != answer:
await ctx.send('Your punctuation or spelling was incorrect. Try again!')
it only checks for a message once
i want it to check messages until the timeout
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
it has the timeout kwarg
confusion
you want it to wait for a msg until a certain time?
basically i want it so if the guess is wrong it will continue to wait for messages
currently it only waits for the first message
what you need to do is check if the message content actually equals the answer string
otherwise it just waits for the first message sent in any channel
if message.content == "str"
no, he should add it into his check function instead
ah sorry didnt know what you ment
and no your wrong
hes waiting for any msg if its wrong it sends a msg that its wrong if its right it continues the action
here's the problem with that:
wait_for will return the first event that meets the check criteria
so if he's not testing for the correct message.content in the check function it will just return for one single message and none that come after
check = lambda check: if message.content == "msg"
that just checks for that msg only
but as said on msg alone checks for any msg you would have to do a check for that msg
thanks guy
ok
tbh here i like using ``py
(i dont care its not async) will else fire even if its not able to connect? py if r.text == "1": role = bot.get_role(config["user_role"]) await bot.add_roles(ctx.author, role) else: await ctx.send("You are not registered on https://karen.pics/ .")
zz
wdym
!pypi disnake
if message.content in [''] :
so you can add more options in there
i like to do that for a list of admin ids so that it restricts commands to admins
or if author.id is in
basic py he can do it himself
¯_(ツ)_/¯
in this case you should've been matching against the correct string he defined earlier:
check = lambda check: if message.content == answer
there isn't a list of strings it should match against, it's just one
just use the command decorator for roles or perms lmfao
probably his bot is just for his server
i think he doesnt have much context as he wants the wait for a msg that if correct it does an action if not it sends something and continues to wait for
i get this
guess = await client.wait_for('message', check = lambda check: if message.content == answer, timeout=timer)
^
SyntaxError: invalid syntax
sorry wrong thing sent
that would only wait for a msg that starts with what answer contains
so if answer is a string it would wait for that str
no, that would wait for a message that is exactly equal to what answer contains
yeah mb
that's literally the point of his code, he made a typing speed test
ok didnt know about it?
@slate swan
dont use a lambda tbh
use a function in this case
def check(msg):
if msg.content == answer and msg.author.id == user_id:
return
how would i send a msg if it the content is not the same as answer
def check(msg):
if msg.content == answer and msg.author.id == user_id:
await msg.send("correct")
else:
await msg.send("incorrect")
i think this can work im not sure
nope
SyntaxError: 'await' outside async function
yeah lol just noticed
ig set a var value and send the var ig
im just confused rn with lambda and im having a headache
What library do you recommend?
???
I heard discord.py is no longer supported
discord.py still works fine, but if you need to you can use pycord
disnake too or hikaru
Okay
^
If you want to try out an entirely different library than dpy, then hikari is a very good choice
If you want to use a fork with stable and updated features, use disnake / nextcord
It will go away by doing nothing in a while
Though stop spamming the api lol
It might be from the host if you use one
pycord

Hi my host isnt logging me to my discord or is not authorizing to login it says
Do you know how to fix it?
redirect_uri 
how to make a bots message that the author can only view
bot sends a message
only author can view it
ephermal kwarg
whats an ephermal kwarg
It can only be done through an interaction
Not through
But in response
So you can't do it with your everyday command
does guild.members contain offline members? ex if i use py for member in ctx.guild.members: print(member) will that print offline members too?
I don't see why it wouldn't
normaly u cant get offline members with a member fetch
at least with selfbots u cant
i wasnt sure with normal bots
i didnt
on bot making threads people always talk about fetching members and they couldnt find out how to fetch offline users i think
ok
how would i make the bot send a dm to a certain person
this is my code
async def on_message(message):
user = client.get_user(12345678)
if user_message.lower() == 'dm':
await message.user.send("stuff")```
i still dont get ephermal kwargs
Yes
What redirect url do i need to make it work?
hmm ok
ok
how do you check if a message replying?
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
If no message is mentioned it will return None
@final iron i still cant figure ephermal kwargs
It can only be used within the context of an interaction iirc
!d discord.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
can it be like !hello and it sends back an ephermal kwarg
No ephermal kwarg
oh okay
You only get ephemeral messages with interaction responses
so like a clikc
so it wont return an ephermal message if i do !hello
like u cant make it return one
No
oh
r u making a bot?
Oh, I haven't even made moderation commands yet
Yes
also heres another idea, giveaways
after u make moderation commands u can work on that
How many messages can a bot iterate through in channel's history?
There must be some kind of limit
You mean a ratelimit?
i guess
okeei
@client.event
async def on_message(message):
if message.content.startswith("dm".lower()):
dm = await message.author.create_dm()
await dm.send("stuff")```
you should probably use the commands portion of discord.py tho
in that it would be more like:
@client.command()
async def dm(ctx):
dm = await ctx.author.create_dm()
await dm.send("stuff")```
@left crater
i tried that in my program and it didnt work so i just made the dm
I'm very stupid (
I've been having trouble putting in the code. So I've created a "bad word" restriction and it works the way I want it too but however I want to have exceptions for example MODS can say the words but the Members cannot. (I had a bit of help from a youtube video).
async def on_message(msg):
for word in bad_words:
if word in msg.content:
await msg.delete()
await bot.process_commands(msg)
if msg.author.has_permissions.manage_messages:```
How far I got
So if the msg.author has the manage_messages permissions I want it to ignore them
Ping me when you can help
Any help ? (Python version : 3.9.9 / Hosted on Pterodactyl)
P.S. : Ping me if you can help :>
well, are you using dpy or pycord
I installed py-cord
i dont want it to send it to the author
i want to send it to a certain user by using their discord id
i want to do a slight bit of trolling on my friend
kinda like this python async def dm(ctx, member: discord.Member.id): dm = await member.create_dm() await dm.send("stuff")
this should work i think
ok
you would use it like (prefix)dm (discord user's id)
do i just add an if then function before dm.send
so does discord.Member.id convert the param into member object?
like if user_message.lower() == "dm"
yes
didn't know that notations work like that
no
it just tells us what class the thing belongs to
or in this case is supposed to belong to
gl
could you do this?py @bot.command() async def kick(ctx): Member = await ctx.guild.fetch_member(ctx.message.reference.author_id) await Member.kick(reason='Bye bye')
by finding the person that sent message that you replied to, and kick them?
kicks the ctx.author?
no
nvm i suck
the author of the message that you replied to
@left crater are you ok with just using discord.Member class and then using the code to generate the id
@client.command(aliases=['dm'])
@commands.has_permissions(administrator=True)
async def mp(ctx, user: discord.User, *, value):
await user.send(f"{value}")
print("Message sent")```
You can use that
or you can listen to this pro
👀
^^^
he wants to use the id though
Should work? 😂
yes
yes i think
you should convert the param member to int, then fetch the member id
at least that's what i do
!dm <user> [message]
!dm (members discord name and his gamertag) (your message)
Oops
ok ill try it
File "C:\Users\nick\PycharmProjects\pythonProject\main.py", line 91, in <module>
@client.command(aliases=['dm'])
AttributeError: 'Client' object has no attribute 'command'
client
use the other thing
discord.ext.commands.Bot()
like @botname.command
you defined client as discord.Client() right
but you gotta do discord.ext.commands.Bot() to do this one
and define your command prefix
@mp.error
async def mp_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You can use that command, you don’t have the perms !")
await ctx.message.delete()```
Error message if you don’t have perms
as a kwarg of your client
you might want to add asyncio.wait(3) before you delete
something like python @mp.error async def mp_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You can use that command, you don’t have the perms !") await asyncio.wait(3) await ctx.message.delete()
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='+', help_command=None)
token = "TOKEN_HERE"
@client.event
async def on_ready():
print("Bot is ready!")
await client.change_presence(status=discord.Status.online,
activity=discord.Game("+help"))
@client.command(aliases=['dm'])
@commands.has_permissions(administrator=True)
async def mp(ctx, user: discord.User, *, value):
await user.send(f"{value}")
print("Message sent")
@mp.error
async def mp_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You can use that command, you don’t have the perms !")
await ctx.message.delete()
Here it is
change the command_prefix to your bot prefix
Me when spoon feeding
god damn
¿
also where do u learn the discord library
Docs
what is this
skill
not skill
skill is when you subclass Bot like me and others
and that bot constructor why that bad naming smh
thats like naming a lemon an apple
and dont change your presence on ready smh use the kwargs for it
I keep on getting an attribute error
async def on_message(msg):
guild = msg.guild
if msg.author.permissions.manage_messages:
# does nothing (skips)
...
else:
for word in bad_words:
if word in msg.content:
await msg.delete()
await bot.process_commands(msg)```
Everytime the event is triggered this shows up in the console
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
and use a member obj tbh
no
dpy doesnt have slash commands
mee6 has a private api wrapper probably


