#discord-bots
1 messages · Page 439 of 1
message.content 

Tysm
did it work?
Haven't test it, like I said I'm not on pc
ah my bad
?

!d discord.PermissionOverwrite
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
`x == y` Checks if two overwrites are equal.
`x != y` Checks if two overwrites are not equal.
`iter(x)` Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
PermissionOverwrite, yes
I guess you can do it by using APIs
try await ctx
oh yeah
the bot needs admin
as its changing roles
and permissions
you can set it to be admin in the developer page
but give it a admin role and try
Manage Channels permissions should work

How do I get my bot to detect when a user has changed their status to contain certain words?
I have all intents enabled
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
Hi, so I have the following code or line
cur.execute(f'''INSERT INTO GUILD_{ctx.guild.id} (user_id) VALUES ({x.id})''')
``` and i need it to ignore if the(user_id) already exists
i strongly suggest avoiding the use of f strings in sql queries
you can get into some nasty sql injection problems
I'm not sure if this is the appropriate place to ask about SQL
#databases should be better
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
but what do I input? Like I want to check if there status contains certain words
Check if their new status contains a certain word?
How do I edit embed?
Does it even make sense to have access and do not have access to something at the same time
yes
You can pass embed to edit()
I mean that's exactly what you would do
I want to make it where if they have a servers vanity invite, to give them a role
Ok
Soo I use
embed.edit()
Can I do the bot to transmit video when connected to a discord channel?
@client.event async def on_member_update(member): role = get(member.server.roles, name="Test") if member.status == 'discord.gg/': await client.add_role(member, role) Like this?
embed kwarg
nice indenting
ADS is ready to moderate.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Orange\Desktop\ADS custom discord bot\ADS.py", line 181, in on_message
await level_up(users, message.author, message)
File "C:\Users\Orange\Desktop\ADS custom discord bot\ADS.py", line 202, in level_up
levels = json.load(g)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 2 (char 1)
``` what is wrong
on_member_update takes two params
before and after
Your JSON file is invalid
Probably empty or sth ig
see
not working
ADS is ready to moderate.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Orange\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Orange\Desktop\ADS custom discord bot\ADS.py", line 181, in on_message
await level_up(users, message.author, message)
File "c:\Users\Orange\Desktop\ADS custom discord bot\ADS.py", line 202, in level_up
levels = json.load(g)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 2 (char 1)
``` seee
still
Are there any docs or something more specific to learn how to use discord-py-interactions?? Because the official documentation web isn't working and isn't enough with the examples give in GitHub
@bot.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 882642949287051265:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'Roblox':
role = discord.utils.get(guild.roles, name='Roblox')
elif payload.emoji.name == 'Minecraft':
role = discord.utils.get(guild.roles, name='Minecraft')
else:
role = discord.utils.get(guild.roles, name=payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
print("Completed")
else:
print("Member not found")
else:
print("Role not found")
@bot.event
async def on_raw_reaction_remove(payload):
message_id = payload.message_id
if message_id == 882642949287051265:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == 'Roblox':
role = discord.utils.get(guild.roles, name='Roblox')
elif payload.emoji.name == 'Minecraft':
role = discord.utils.get(guild.roles, name='Minecraft')
else:
role = discord.utils.get(guild.roles, name=payload.emoji.name)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)
print("Completed")
else:
print("Member not found")
else:
print("Role not found")```
NameError: name 'client' is not defined```
what am i doing wrong?
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ty
you didn't define client and you used client in your code @slate swan
Yes
Hello...
Is it possible to get the remaining cooldown time of a mentioned Member?
Like if a member used f!daily which can be done every 24 h
Is it possible for others to see how much time is left for that member?
!d discord.ext.commands.CommandOnCooldown.retry_after
The amount of seconds to wait before you can retry again.
if im using bot instead of client do i use
discord_client or discord_bot
bot
it will work?
Yeah but of a mentioned user?
....
sorry im new ;-;
Has anyone tried hikari?
guys how can i convert string of message object to message object ?
huh
Eh, I am gonna use disnake, so no hikari
....
well if you are looking for a alternative to dpy for 2022, you can try enchanced dpy
I was trying a to create a command that will get a mentioned user remaining time
?
Hmm, I'll look into it
Hmm, u gotta use some internals like get_bucket and stuff. Just like in an on_message cooldown
somebody can help ?
Okk I will see!
U gotta send that as a message dude...
https://pypi.org/project/enhanced-dpy/
This right?
Okay
no something like this
'<Message ....>'
to
this
<Message ....>
Indeed lmao
guys how can i convert ?
'<Message ....>'
to
<Message ....>
str to message object
how to check whether a message is available?
Good morning ! I would like to know if it would be possible to use Pydroid to run a program acting on discord, and if so, how to link Pydroid to discord? On computer, I used my terminal to link the two, but on Android I have no idea how I could do it, and if it would even be possible! Thank you in advance for your answers
Another question ... If this is not possible, would you have a python program hosting solution other than Heroku which only offers 500h of activity? I headed to Naglito, but at the moment their servers are all in use, and unfortunately I can't find any other hosting solutions at the moment.
??
I have a question
why does it start with good morning and end with evenning
check does the eval() function help you or not
the first one is a repr
you already have the object if the repr is printed or something
put the string in the eval() function
!d object.repr
object.__repr__(self)```
Called by the [`repr()`](https://docs.python.org/3.10/library/functions.html#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](https://docs.python.org/3.10/reference/datamodel.html#object.__repr__ "object.__repr__") but not [`__str__()`](https://docs.python.org/3.10/reference/datamodel.html#object.__str__ "object.__str__"), then [`__repr__()`](https://docs.python.org/3.10/reference/datamodel.html#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
wdym try to get the message
lol you changed it
Yeah
Hello im having trouble on this code
@client.event
async def on_ready():
print("We have logged in as {0.user}")
.format(client))
error message:
File "main.py", line 9
.format(client))
^
SyntaxError: invalid syntax
can someone answer my question please ...?
can you send to me code of this ?
what
code of convert
you cant
please answer if you know the problem
why ?
.format is a line down?
how can i save a object in json ?
don't use .format, use f strings
why do you want to do that
are you saving a message object?
yes
if you are, save its id and fetch it later when you need it
now its displaying this
File "main.py", line 9
'.format(client))
^
SyntaxError: EOL while scanning string literal
thanks
eval('<Message ....>') did it work?
that wont work
so u wanna use pydroid to simulate gestures and stuff?
in your phone?
?tag vps
aws?
wrong server
Aws ?
aws
It's free ?
yes for one year i guess
they offer 1 year free plan with 750 hours worth of servers per month
np
I will try to do that
mk
is it difficult to do?
depends on your age
if you are a adult it will just require you to verify your credit card 😅
I'm a minor 😅
Shit
well, if you are an student, just ask for your mom's or dad's credit card
it won't cost you anything, it's just for verification
there are no other solutions / sites?
welp, if you have a microsoft student email you could try azure
AWS doesn't need credit card if you are a student
student verification requries a arm and a leg
You need to send proof of begin a student
its god damn hard
Yeah ik
¯\_(ツ)_/¯
raspberri pi latest model from 100 bucks can handle around 2k servers
Wow
guys how can i get message with id ?
noice
uses your own internet speed tough.
Hum thanks for your answers, I'll try
but does it require restarts?
heat issues and stuff?
and as of my country, we have 1MBps connections
yup
like once per 6 months i good to update the linux software
?
so, self hosting is not a good feat when internet is bad
have you tried it?
async def ticket(ctx):
guild = ctx.guild
member = ctx.author
admin_role = get(guild.roles, name="Admin")
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(f"ticket-{str(ctx.author.display_name)}", overwrites=overwrites)
AttributeError: 'NoneType' object has no attribute 'id'
this gives this error
h e l p :(
No but the specs are just like that
how can i get current time in a var?
import pytz and date time
-_- why
help me with this
use return (variable name)
do u know the code?
yup
show it then xD
lol sure
does anybody know the solution for this problem
it doesnt read the message (start) it just ignores it and it doesnt give me a error
@client.event
async def on_message(message):
if message.content == "start":
channel = await message.guild.create_text_channel("newchannel")
await message.channel.send("start 2")
distro?
Intents?
whats that?
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
!intents
ok thanks
?
anybody heard anything about discord.py being deprecated/archived by its creator?
Yes
with which distro? (6 month updates)
appreciate it
there was a quite a big discussion few days ago
check out the pins
Any, doesn't really matter maintenance is needed
tyty
tho debian would run for eternity without touching it after fired up 🥲
From datetime import datetime
Time = today.strftime("%I:%M")
Print(time)
@floral jacinth
can someone help me how to make a token hidden to the public?
oh great
why would the token be public?
You mean hide it in your code?
Use os.getenv() (you need to do import os first)
thanks
just put it in a file and ignore it in git
for example, bot.run(os.getenv('token')) ('token' is just the name of the variable, the variable's key is hidden in that variable)
guys how can i get content of message in self-bot ?
wait so i just do os.getenv('token')
yes, should return the variable's value
no doesn t work in self-bot
then idk sorry
what's self-bot
what's the library
We don't give help here regarding a self-bot this is against ToS
Please stop mentioning this here.
we dont have ctx in on message
yep. also lemme contact modmail rn LOL
there
This is not a offense, perusing it is. We have now said to him that is not allowed.
sent :D
yeah
yup
deleted
no need to get him banned
its against discord tos
yeah
I mean no need to do that 😅
yeah i know what you mean
No, breaking ToS will get a verbal warn first. Then if he/she still ask about it after a verbal warning it will be a mute etc.
kk
oh right
is using discord bot clients against tos @cloud dawn
yes?
Discord bot clients are perfectly fine.
They've been cracking down lately, I've heard
My bad. I thought he was asking about self bots
you mean super duper fine?
Yes commands.Bot also uses Client it is inherited.
I thought there can be restrictions because u can misuse the power given to the bot by using the discord bot client
@dusky patio Hello, as per rule 5, we will not help with self bots as they are against Discord's ToS. Please re-read our rules.
I don't think i understand you, using a bot token from the discord portal is fine. Using your own client token is not fine.
@languid jungleWe need this for a good job, not an illegal one
It's not illegal it's against ToS, disregarding of the task.
altho you mean no harm, law is law my friend.
if it's against tos, it's illegal right?
I mean this one https://github.com/Flam3rboy/discord-bot-client
you agree to tos when making your discord account, its a legal agreement
No a ToS is not going against the law. They can ban you from the API and send a warning to the user. If the user will not comply the company can make a Cease and Desists letter (Most likely will not happen). Take Groovy for example.
It's not like abusing the API will have the FBI raid your house.
elif isinstance(error, commands.MessageNotFound):
await ctx.send(f"**Error!** You must use this command in the same channel the counter is in")
can someone tell me why this doesnt catch the Message Not Found error
just because something is illegal does not mean the fbi will raid your house
how to remove a cog completely from help command
kwarg hidden inside a class instance
is this how im supposed to run a enviroment variable on repl
client.run(os.environment("token"))
ok so how do I filter it in send_bot_help
like shud I just use hidden=False in the class
I think you can do that lemme check
ok lemme try it out
Could you dir mapping?
Can anybody help me?
I've been trying to get this command to work for 20 minutes but I can't
@bot.command()
async def stop(ctx): # TODOS LOS SERVERS
voice_client = ctx.message.guild.voice_client
user_channel = ctx.message.author.voice.channel
bot_channel = bot.user.voice_client
if not ctx.message.author.voice:
await ctx.reply("**{}** necesitas estar conectado a un canal de voz".format(ctx.message.author.name))
return
if voice_client.is_connected():
if user_channel and bot_channel == voice_client:
channel = ctx.message.author.voice.channel
await voice_client.disconnect()
EmbedMusic = discord.Embed(tilte='\n', description=f':octagonal_sign: {ctx.author.mention}, Me salí con éxito de <#{channel.id}> ', color=0xcd5c5c)
await ctx.send(embed=EmbedMusic)
else:
await ctx.reply("**{}** ya estoy conectado a un canal de voz".format(ctx.message.author.name))
if voice_client == None:
await ctx.reply("El bot no está conectado a ningún canal de voz")```
Erros ->
Ignoring exception in command stop:
Traceback (most recent call last):
File "C:\Users\vixez\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\vixez\Documents\WOLFM00N\DISCORD\BOTS\JapanWave\CODE\py\pruebas.py", line 1108, in stop
bot_channel = bot.user.voice_client
AttributeError: 'ClientUser' object has no attribute 'voice_client'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\vixez\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\vixez\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\vixez\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ClientUser' object has no attribute 'voice_client'```
dir?
print(dir(mapping))

bot.user.voice_clients
It's a list
and what i cant change to my bot work
its a dict
oh ok
How do I paste it into the embed! for example??
Heya, how do I prevent mass mentions? I know how to use len(). But dont know what to type.
message.mentions is a list
!range-len
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
Just notice how the len is used disregard the for loop.
How can I paste!? like this
So
if len(message.mentions)
👍
Alright
[#help-carrot](/guild/267624335836053506/channel/696840664435916950/)
Just copy this
so..i want to make my discord bot open source, should i put a license on the github repository? and if yes what license do u think fits well?
ok sorry i will remove it
for example.
Alright
?
anyone here moving to rust
len(bot.guilds)
id_list = [guild.id for guild in bot.guilds]
any good module or sm api for anime search commands?
you can use my api wrapper for anilist (you can find it in my github) or make your own
how would i go about making a poll command? struggling about how to pass in 2 different options and put them on an embed?
What do you got so far?
@client.command()
async def poll(ctx, *, text):
pollEm = discord.Embed(title='Test',
color=discord.Color.random(),
description=text,
timestamp=datetime.utcnow())
pollEm.set_author(name=f"{client.user}", icon_url=client.user.avatar_url)
await ctx.send(embed=pollEm)```
What is the result?
i wanna add like 1️⃣ and 2️⃣ on different lines of the embed if i can figuree out how to take in 2 separate things and display them, maybe seperate both options by a ,
well it displays an embed
do something like (ctx, *polls):
and takes in a text
polls will be a tuple then
text is a tuple
what
!e ```py
def somefunc(*, someargs):
print(someargs)
somefunc('a', 'b', 'c')
???
What are the requirements to program the bot?
?
Try it in a discord bot somehow it's valid.
I know but his method also weirdly works i've tried.
doing *, polls will make polls a keyword argument
someone told i could use voice_bot instead of voice_client
it doesn't work it says, Context has no attribute voice_bot
what do i do?
ok whats the case that it turns into a tuple
ctx.voice_client
!d discord.ext.commands.Context.voice_client
voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
since i've used bot instead of client everywhere will it word?
work
No idea since the source is pretty long
you tried it but you have no idea
...
can 2 members own a guild?
https://www.vultr.com/docs/how-to-run-a-python-discord-bot-on-a-docker-application
This runs it 24x7 right?
So I have a debug command to see what permissions my bot has. I used {dict(ctx.me.guild_permissions)}.
How can I make it so that if a permission is true then it will do something else with it and not send it. And if it's false it does send the permission it needs?
How to set a command on the user ?
yeah, vultr is overprices though.
Use a command on a user?
Is that what you mean?
For example, I want to set the Clear command for my user that only I can use
So just do a check to see if the command user is the owner.
I know about the roll, I do not know only about the user
watt ?
So do what I said. Or instead of checking the owner, just see if the person is an ID. You would make the user's ID a int.
I just gave you the answer in two different ways.
tnx for help 
You're welcome
you mean logging?
Yeah, to log those events
use the on_member_join event
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!source
yes
on_member_join(member) and on_member_remove(member)
!d discord.on_member_join 
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Ty : )
also, the bottom part is important @spark dragon
make sure to have intents on
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
how do i get my bots uptime in the new timestamp formate??
How I add the pfp of the person that did the command and the time in the footer?
@bot.command()
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount : int):
await ctx.channel.purge(limit=amount)
emb=discord.Embed(title="Messages deleted successfully", description="🧹")
emb.add_field(name=f"Responsible moderator : {ctx.author.name}", value=f"Responsible channel {ctx.channel.mention}")
emb.set_footer(title= #pfp | "Today at" #time,)
msg=await ctx.send(embed=emb, delete_after=4)
how do i get the default channel of a server?
@bot.event
async def on_message(self, msg):
if is_bot:
return
data = await get_leveling_data()
xp = data[f"{guild.id} - {user.id}"]["xp"]
lvl = data[f"{guild.id} - {user.id}"]["lvl"]
to_the_next_lvl = data[f"{guild.id} - {user.id}"]["to_the_next_lvl"]
if len(msg.clean_content) > 3:
xp += 1
if xp > to_the_next_lvl or xp == to_the_next_lvl:
data[f"{guild.id} - {user.id}"]["xp"] = xp - to_the_next_lvl
data[f"{guild.id} - {user.id}"]["to_the_next_lvl"] = round(to_the_next_lvl ** 1.02)
data[f"{guild.id} - {user.id}"]["lvl"] += 1
data[f"{guild.id} - {user.id}"]["user's_last_message"] = str(cnt)
data = await get_public_leveling_data()
xp = data[str(user.id)]["globalxp"]
lvl = data[str(user.id)]["globallvl"]
to_the_next_lvl = data[str(user.id)]["globalto_the_next_lvl"]
if len(msg.clean_content) > 3:
xp += 1
if xp > to_the_next_lvl or xp == to_the_next_lvl:
data[str(user.id)]["globalxp"] = xp - to_the_next_lvl
data[str(user.id)]["globalto_the_next_lvl"] = round(to_the_next_lvl ** 1.02)
data[str(user.id)]["globallvl"] += 1
data[str(user.id)]["globaluser's_last_message"] = str(cnt)
await bot.process_commands(msg)```
Do someone know why isn't it adding to the user xp?
.
embed.set_thumbnail(url=ctx.author.avatar_url)
How can I add it to footer
?
Like this
i am not sure about this wait lemme check
Okay
icon_url
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
@slate swan
!d discord.ext.commands.Context.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message").
New in version 1.6.
Does this
reply to msgs like users do (like I am doing here)? or is it literally just to send a normal response? and if it is the former; does it ping on reply by default or do I have to do somehting to make that happen
it replies to the message, and pings
okay cool
to send a normal response its just send()
yeah i was looking for the reply and ping one, just checking i understood it right
so I tried that and it's just sending the msg in the same way as send() does and the bot's not pinging nor replying to me
Code?
@commands.guild_only()
@commands.command(description = "Show the status of a member or of yourself.", usage = "status [member]", aliases = ["us", "user-status", "member-status"])
async def status(self, ctx, *, member: discord.Member = None):
member = member or ctx.author
if member.activity is None:
member_status = "No status"
else:
member_status = member.activity.name
embed = discord.Embed(title = f"{member.name}#{member.discriminator}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
embed.set_author(name = f"{member.id}", icon_url = member.avatar_url)
embed.set_thumbnail(url = member.avatar_url)
await ctx.reply(embed = embed)```
Uhhhh
did you restart/reload the cog for the changes to apply?
You saved the changes?
Try to restart your bot
Bruh autocorrect
yeah i reloaded the cog twice, i'll try a bot restart. yes I saved
okay reloaded the whole bot and it's still doing the same thing
nope

okay all good. I done goofed and was reloading the wrong file 😂 😠
!source
@commands.command()
async def a(self, ctx, member: discord.Member):
await ctx.message.delete()
await ctx.send(f"ehi {member.mention}, {random.choice(insulti)}")```
why it doesn't delete the message sent by user
await it
any error?
#bot-commands @crude crow unless you're helping anyone
!random
what are you trying to do
nothing i fixed it
guys anyone know how i can send ephemeral messages aka Only you can see this embeds ?
You need InteractionResponse object
on discord.py i tried doing the
publish()
command and for some reason it wont work
is there any restriction on this command or smth
can i not send embeds?
can you point me to some example on that mate?
Okay hey @bronze wigeon how should I get started considering I know nothing about python or discord bots
I need this asap
But I don't know nothing about python or stuff
We have suggested how to get started, youtube, you can use the resources in !resources, you can use https://automatetheboringstuff.com, lots
I'm desperate you can say
I could tell
Okay how much time shall it take before I can finally make a discord bot for my server considering my condition
I can't answer that
it depends on how you learn and how well you learn it
whats your condition
Well I might be honest I'm not a really fast or good learner
I dunno nothing about discord bots or python and I wanna make a custom bot
As soon as possible
why
Then it may take awhile, it may take months, weeks, years, it's not immediate
Years!?
Depends how well you learn, usually it doesn't take over 2 months to learn alot but
Cause the current developer in the server is stepping down and I wanna learn and make the bot
But I know nothing
you aren’t obligated to take the spot of developer
take your time, learn python and then become a dev for that server
Yeah that's what I'm trying
You clearly aren't
But I wanna do it fast don't wanna take much time
you’re trying to jump in discord.py without any knowledge
Why?
You can't avoid it taking time, if that were the case programmers would be obsolete
did you ever code? other languages
I assume you're talking to Luminity?
yes
I Just need the knowledge nessaary for the bot development dibugging and stuff no other use of it from me in real life
How much Python do I need to know?
discord.py is ultimately a complicated Python library for beginners. There are many concepts in there that can trip a beginner up and could be confusing. The design of the library is to be easy to use -- however the target audience for the library is not complete beginners of Python.
With that being said, beginners tend to use this library quite liberally anyway and while I appreciate the endeavour and tenacity it should be noted that asking for help here does take up the valuable time of volunteers. As a result certain knowledge is required before you can actively participate in the help channels:
- The difference between instances and class attributes.
- e.g.
guild.namevsdiscord.Guild.nameor any variation of these.
- e.g.
- How to use data structures in the language.
dict/tuple/list/str/...
- How to solve
NameErrororSyntaxErrorexceptions. - How to read and understand tracebacks.
This list is not exhaustive
If these concepts are confusing -- please feel free to complete a smaller and simpler project first before diving into the complexities that is asynchronous programming in Python. The Python help channel (#738572311107469354) or the Python server (https://discord.gg/python) could also be a place to go for basic Python help.
read that
Used to know a bit of java back in school sucked at it tho but now when I look back at it I think it was quite easy I just didn't wanna do it or try to understand it
In order to get that knowledge you need to know python or else it'll be like trying to type spanish when you only know english
You're essentially trying to run before trying to walk
So learn to walk, before trying to run
Hopefully that makes sense
I don't wanna do that positively but I wanna do it fast it's just that :((
You'll get confused on how to fix any errors if you don't know what the errors mean, and python helps you also learn those errors
You're trying to become the top dog in programming for that server but it's not that easy
if you do it as fast as possible it’s probably going to take you like 3-4 weeks
for discord.py
3-4 weeks seems nice a year seems horrible
async programming is going to take you a while though, it’s really complicated
That's assuming you only learn discord.py and don't take too many breaks
Async?
Those 3-4 weeks are gonna be a pain and quite intensive if you don't even understand the basics though lol
Exactly
asynchronous
You will be stuck for an hour on something such as indentation
It doesn't matter the speed imo, rather the efficiency
You would need to learn python asynchronous stuff before trying discord.py because, you'll get very lost very quickly
and you could use non-async functions however, it won't work very well
I'm not trying to push myself too much as I have University stuff also but still how much shall it take on an average
I want to learn it fast but when I think of it the way I rate I wanna learn it at doesn't comply with my life
If your doing university why are you branching into something new and vast as programming? It will take a lot of your university time
I have other stuffs
Because I want to make a bot
You will most likely not be able to learn it in enough time to get this new developer spot, unless you risk your University Education to code a discord bot for a server just to not even be 100% likely to be accepted into making said bot
So it's a bad idea then?
focus on your uni for now
Because to my knowledge you have to like, make a bot and prove you are able to make a bot for them, which may mean you spend all your time learning, just to not even get that 100% chance of being accepted
when you have more free time, start with python
If your university offers, why not take a python class or something alike
Nah I'm doing medicine enough load already
bruh
And above that it doesn't give python classes
Medicine > Programming
If it would have I sure would have gone
then get comfortable first and then you will see if you actually have time
yeah let’s just switch to that
Are you sure I see programming as the future tho
then why did you do medicine
programming isn't 100% to make you decent income
it's mostly based on commission
what you just said is contradictory to your actions taken
where someone will pay you to make something
If I want to have by bot use the reply feature to reply to a msg but I don't want it to ping \I'd need to add reply(allowed_mentions = False right?
Because as said earlier I used to learn Java back in school but I wasn't really good at it so I dropped
I only want to learn it for the bot
nobody becomes good at java at lightning speed
So you're taking medicine classes and now you're realizing you want to learn programming? doesn't make sense
I think what you're not understanding is programming no matter how easy will take time, python is the easiest to learn and it will still take time
I don't really like programming that much neither I'm much interested in it I'm Just interested in the bot
C++ will take a long time too, no matter what lang / form of lang it will take over a week
this channel is the most off topic out of any topical help channels in this server lol
You've been bouncing back and forth on "I want to learn how to make a bot" but also "I want to take on programming in the future", I don't think you know what you want to do rn
I want to make a bot sure but I don't wanna take on programming in future I see programming as the future
Get it?
then once you spend 2-3 months learning, after you make the bot those months are going to be wasted
Nah I'll need them to maintain the bot ig
Once the bot is perfect for the server your learning will have been wasted and you'll regret it
Just add an existing bot
They won't maintain the bot, if they're able to maintain the bot they wouldn't have had someone program the bot for them
So I'll maintain it
what if the server dies

what if they figure it out on their own
It's not that a big community lol
So the server is likely to die
Meaning your education is more likely to have been wasted
Maybe yes maybe no
My main focus should be my education nonetheless
I'm not putting programing first
how are you planning to balance bot development and your uni studies
No idea tbh
You'd either need to plan for programming or medicine, not both
what if the server owners demand something big
You will either dedicate your time to learning python that may be useless once that server dies or you will dedicate your time to learning medicine that could save someone's life and make you a good income, so
drop out of uni to make a discord bot 👍
Hell no lol
/s
They were being sarcastic but still
we do believe you should learn medicine before learning a discord bot
Tbh I felt like it was a waste after making a bot
what's the format for the things where it makes
- Something``` Red
and
- Something
Yang or something
Hm
There were codes I saw
Not a code lang
css makes stuff yellow iirc
you can do like ```py
print()
@client.event
async def on_message(message):
await client.process_commands(message)
if message.type == discord.MessageType.premium_guild_subscription:
chan = message.guild.get_channel(channelid)
embed = discord.Embed(color=0x36393F)
embed.set_author(name=str(message.author), icon_url=message.author.avatar_url)
embed.description = "thanks for getting us to "+message.guild.premium_subscription_count+" boosts"
await chan.send(embed=embed)
Alright so,
do yall see anything wrong with this code?
Wth is this
i cant exactly test it multiple times
```diff
- Here's some red colored text!
```diff
- Here's some red colored text!
```hmm doesn't seem to be working rn
discord.py? you can learn if you try

Same lol, it feels boring once you know how to make a good one. But tbh I got a pretty good knowledge of APIs and libs by this.
anyone know if i can send the whole error on the on_command_error event?
Pros and Cons of learning discord.py vs learning medicine
__Learning Medicine__
Pros:
+ You can save people
+ You already paid
+ You get a decent income
+ It helps for yourself
Cons:
+ There aren't really any cons, you learn useful stuff
__Learning Discord.py (and trying to learn it quickly)__
Pros:
+ You learn how to make a discord bot
+ You learn some python syntax (Very little)
+ You may learn to maintain it (until that small server dies)
Cons:
- You don't learn anything helpful for the future
- You waste your time learning discord.py when you could spend it on medicine
- You aren't likely to make a decent income
- You most likely do worse in your medicine
@drifting quest
bruh
But we learnt a lot of asyncio and stuff...
these guys lol
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
discord.py doesn’t really teach you alot of asyncio
what about route 66?
do you know what my name means
speechless
its just asyncio.wait_for or something like that
- You don't learn anything helpful for the future
- You aren't likely to make a decent income
- You learn to program
- Programming pays well
if you do i suggest you not talking about it here lol
Also that
but I have like a lot to learn in asyncio still. Dpy don't have much deep use of it
yeah, but that's what got me interested in it
Mainly why I said it teaches little syntax
if you JUST learn discord.py, it's useless not to mention confusing unless you learn python
You learn things by doing them, if you do enough dpy you'll pick up python as you go
Anyone know why I get this issue with my code
During handling of the above exception, another exception occurred:
File "C:\Users\Twist\Desktop\Coding\Python\Discord Bot\discordbot.py", line 16, in <module>
my_secret = os.environ['DISCORDBOTTOKEN']```
They also want to learn it as fast as possible
And also take medicine classes or classes relating to them, idrk what to call them
But they want to learn discord.py as fast as possible as well as learning medicine which will most def not work well together unless he wants lots of stress
Also, you're not supposed to learn dpy without python
It's a pain which can't be cured by a medicine
Having even a bit of knowledge of python speeds up and makes it easy and dpy actually makes a lot more sense then
Including the async-await syntax
Ok thanks guys specially@bronze wigeon I might do my medical for now might look into this bot stuff somewhere in future
Yea
Does anyone know any good guides for using asyncpraw in discord.py because I can't find any recent ones
i dont think thats actually learning asyncio tbh, unless you messed with the internals of the library and actually understood what goes under the hood within the library
even the library itself doesn’t use much of asyncio
prolly the best way would be just playing with asyncio itself
Speaking of, don't you need the asyncio module to use async functions? or does discord.py include it
Yes, don't kill your busy time with only a bot. If you really like or want to try programming, try to do it in the free time since you're already having a uni for medicine and not really for just making a bot for a server
you use functions like asyncio.run as a main entry point of your program
asyncio is inbuilt- also you don't need to import it unless you're using it directly
Okay thanks
I kinda messed with some internals
Not to mention the server is small so the chances of the knowledge going to waste is very likely
Ah
It doesnt? I would say it does up a to point
nothing too complex but still
ive only seen asyncio.wait_for and asyncio.get_event_loop
I've only seen joe
Knowledge most likely never gets wasted, it's just you prioritize something less important by ignoring more important stuff 
other than creating tasks and stuff
True
During handling of the above exception, another exception occurred:
File "C:\Users\Twist\Desktop\Coding\Python\Discord Bot\discordbot.py", line 16, in <module>
my_secret = os.environ['DISCORDBOTTOKEN']```
Anyone know how to fix this error?
cooldown mapping uses a weird type of semaphore too iirc?
Guys suggest me a cmd for my bot
ok well maybe locks as well
I don't think discord.py uses semaphores
its not an asyncio.Semaphore because danny needed to access something i cant recall atm
You don't have an environment variable DISCORDBOTTOKEN
so he created its own class
I see wonder what caused for this work around
how do I obtain an environment variable?
you would set it
found it
class _Semaphore:
"""This class is a version of a semaphore.
If you're wondering why asyncio.Semaphore isn't being used,
it's because it doesn't expose the internal value. This internal
value is necessary because I need to support both `wait=True` and
`wait=False`.
An asyncio.Queue could have been used to do this as well -- but it is
not as inefficient since internally that uses two queues and is a bit
overkill for what is basically a counter.
How do i make so code doesnt work if channel description not in there int his code:
async def suggest(ctx, *, query):```
what?
@bot.command()
async def suggest(ctx, *, query):
if not channel.topic:
return```
@bot.command()
async def suggest(ctx, *, query):
if channel.topic != 'Make a suggestion by typing !suggest here.':
return
both work
i prefer this
You dont have channel defined by the way
how then ?
You can access channel by ctx
if ctx.channel.topic != "Message here": return
Same as u would expect, but valid one since u dont have channel defined elsewhere
Make sure to replace "Message here"
Hey! I'm working on a fork of discord.py with a team of developers, and we just released slash command support in our public alpha today! If you'd like to learn more about our project, it's in my status and about me page. Our goal is to maintain a sustainable discord api wrapper for python, now that discord.py has been archived.
oops, in the test i ran channel was predefined
It is fine
im on team eqeunos
you should put return on a new line to follow PEP8 standards, even though it isn't required
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 70, in on_message
if "Content Creator Videos" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 83, in test
if "Content Creator Videos" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 124, in on_message
if "Team Recruitment Chat" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 141, in test
if "Team Recruitment Chat" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 222, in on_message
embed_mess = await message.channel.send(embed=embed)
UnboundLocalError: local variable 'embed' referenced before assignment
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 235, in on_message
if "WI" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 253, in on_message
if "NoLI" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 268, in on_message
if "RO" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "main.py", line 306, in on_message
if "NOS" not in message.channel.topic:
TypeError: argument of type 'NoneType' is not iterable
XD
Didnt work
topic is empty
From error, it is.
there is a channel that the bot can see that doesnt have a topic set
you could try
i swear its there
if message.channel.topic and "NOS" not in message.channel.topic:
k
there is a channel that the bot can see that doesnt have a topic set
i'm not saying its that channel
just a channel
Gonna be completely straight with ya bud. Never heard of it
yeah and ive never heard of you before
eqeunos is going to make the best one lol
thats subjective
im not part of his developing team im just moral support
'message' is not defined
Can you both kindly move this to somewhere else ?
its related to discord.py, so no.
async def suggest(ctx, *, query):
embed = discord.Embed(
color=0xff0000,
description=
f":bust_in_silhouette: ❘ **User :**\n\n{ctx.author.mention}\n\n:bulb: ❘ **Suggestion :**\n\n{' '.join(ctx.message.content.split(' ')[1:])}"
)
if message.channel.topic and "Make a suggestion by typing !suggest here." not in message.channel.topic:
return
embed.set_thumbnail(url=ctx.author.avatar_url)
channel = bot.get_channel(880935427123605584)
msg = await channel.send(embed=embed)
await msg.add_reaction("")
await msg.add_reaction("")
em = discord.Embed(
description=
f"{ctx.message.author.mention}  Succesfully sent your suggestion to [#880935427123605584](/guild/267624335836053506/channel/880935427123605584/)",
colour=0xff0000)
await ctx.send(embed=em, delete_after=20)```
We started 4 days ago, have 1k members, and just released alpha
full code so yall can see
Where are you putting code to ?
if ctx.channel.topic and "NOS" not in ctx.channel.topic:
k
or define message by taking ctx.message
eqeunos will be the next best thing, trust me
In this world, if you're not first, you're last
now code works but in all channels
yes because of logic u did
it works in all channels where "NOS" is not inside the channel topic
why is it saying unknown words etc?
How could I go about using a bot token with raw http requests to authorize like, sending a message
can i have discord libraly link to learn?
Pretty sure it is "cSpell" extension giving that error and not related to dpy itself
delete this right now
!d discord.
No documentation found for the requested symbol.
I get this too though
!d discord .
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
If I want to have my bot use the reply feature to reply to a msg but I don't want it to ping I'd need to add reply(allowed_mentions = False right?
allowed_mentions=discord.AllowedMentions.none or smthing
don't think it's that as I keep getting this errorpy AttributeError: 'function' object has no attribute 'to_dict'
okay thanks. i didn't see mention_author anywhere on the docs about the reply command
Reset your token, you just leaked it
nah I edited it by like 2 letters
Still reset it, you made it easy to find the toke. Even if they only have some@of it
reset it
done but why is it not logging join leaves
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
cause that ^
also what theme is that for VSC
so now I just put intents=intents) by the comman_prefix bit
Mhm
How can I make embeds for a discord bot and make it mute members for specific amounts of warn, pls help I'm very confused
@bot.event
async def on_member_join(member):
await member.guild.get_channel(868696187497234435).send(f'hi')
tried coding a join message. the problem is that the bot runs but it does not pop up any sort of message when a member joins the guild
!d discord.Embed for embeds.
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
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/stable/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.
Leme read that thanks guys
Any errors?
i get this everytime someone joins
!d discord.Guild.get_channel
get_channel(channel_id)```
Returns a channel with the given ID.
Make sure that the channel exists.
With the same ID?
yes
Do you have member intents enabled?
Try to print member.
@broken turtle did it work?
I am getting a random not defined error anyone know the solution?
import random
What are you making?
i figured out the solution
intents = discord.Intents.default()
intents.members= True
@bot.event
async def on_member_join(member):
await member.guild.get_channel(868696187497234435).send(f" Hi and welcome to the server {member.mention}")
Epic
hey in the await what are those numbers you wrote?
Because im trying to make somrthing similar to you
something*
A channel's id.
how can you check that
Right click a channel and click "copy id".
How to make it where i @botname and it responds with a message
oh ok
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
Make sure to have developer mode on!
Thank you!
@somber musk Settings > Advanced
Its a channel id
ok leme tryu
hey for your code did u have to import anything new for the welcome of new members? im trying to make a similar bot as u
Where is the discord bot module documentation?
where it talks about most of the import stuff
thats my code, what did i do wrong to make it not work
import discord
from discord.ext import commands
import datetime
from urllib import parse, request
import re
import asyncio
import sys
this is what my imports are
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
oh ok ty
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
that shows the very basic stuff? nothing to do with code?
This is the documentation?
it just shows how to invite a bot
My bad, here are the docs: https://discordpy.readthedocs.io/en/stable/api.html
ty
how did you use those imports in your code, also which import is just for the welcoming join? because i dont think i need the others in my code
I dont know. It just works tbh
wut
@somber musk what error are you gettung
There's no error it just doesn't work and says half the imports aren't used
Like the imports you told me
@commands.Cog.listener()
async def on_message(self, message):
with open("./veriler/antispam.json", "r") as config:
data = json.load(config)
if data.get(str(message.guild.id)) == True: #errors
def check (message):
return (message.author == message.author and (datetime.datetime.utcnow() - message.created_at).seconds < 15)
if message.author.guild_permissions.administrator:
return
if len(list(filter(lambda m: check(m), self.client.cached_messages))) >= 8 and len(list(filter(lambda m: check(m), self.client.cached_messages))) < 12:
await message.channel.send(f"{message.author.mention} Lütfen Spam yapma!")
elif len(list(filter(lambda m: check(m), self.client.cached_messages))) >= 12:
embed = discord.Embed(title = f"**Kullanıcı atıldı {message.author.guild.name}**", description = f"Sebep : Spam.", color = 0xff0000)
await message.author.send(embed = embed)
await message.author.kick()
await message.channel.send(f"{message.author.mention} Spam yaptığı için sunucudan atıldı !")
Not worked
That's bc what you're trying to do doesn't need all those imports
event part, but there is a problem in the database part, it does not prevent spam
Ya ik but it doesn't work without the imports
^
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
it takes in two arguments
Unused imports don't affect the code
what do I put for the 2nd argument
Read the docs
this
the docs explain it well
Parameters do
@hasty iron okay so now it shows that I have updated my account information with the message I gave however doesn't show change was made
@bot.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
if member != None:
embed = discord.Embed(
title=f'{member} has been Banned',
description=f'{member.mention} has been Banned',
colour=0xf6dbd8
)
embed.add_field(name='Reason :', value=f'{reason}', inline=True)
embed.set_thumbnail(url='')
embed.add_field(name='Banned by :', value=f'{ctx.author.mention}')
await ctx.message.reply(embed=embed)
if member.id is None:
eeee = discord.Embed(color=0xf6dbd8,
description="Ban")
eeee = add.add_field(name="Usage", value="``^ban [Member] [Reason]``")
await ctx.send(embed=eeee)
return
if member.id == ctx.author.id:
e = discord.Embed(color=0xf6dbd8,
description="Error | you cannot ban yourself")
await ctx.send(embed=e)
return
if member.top_role >= ctx.author.top_role:
ee = discord.Embed(color=0xf6dbd8,
description="Error | you cannot ban that user")
await ctx.send(embed=ee)
return
if reason is None:
reason = "no reason provided"
return```
how can i adjust the source so that when someone does ^ban it replys with the command usage instructions? as seen i have it defined as eeee, but it dosnt work for some reason
the ban function itself is fine, but its the if bits that dont work
you have to check it on a command error handler
that's what I did
commands.MissingRequiredArgument
So im creating a command with asyncpraw and im wondering if its possible for the user to be able to choose which subreddit the image is coming form?
Like a command ?subreddit meme
Then it displays an image from that subreddit
Wait nvm I did it
File "C:\Users\Twist\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Twist\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Twist\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: mutual_friends() takes 1 positional argument but 2 were given```
Anyone know how to fix this?
trying to get mutual friends via .mutuals @
send the code?
@client.command()
async def mutuals(ctx, member: discord.Member):
await member.mutual_friends()
what are some recommended hosting sites for a discord.py bot? I'm using contabo but it goes down way too frequently + they don't have 24/7 support
@bot.command()
async def poll(ctx, question, option1=None, option2=None):
if question is None:
await ctx.reply(f"`Usage` - ^poll \"Question\" \"Option One\" \"Option Two\"")
else:
await ctx.channel.purge(limit=1)
embed = discord.Embed(title=f"New Poll", color=0xf6dbd8)
embed = embed.add_field(name="Question:", value=f"**{question}**")
embed = embed.add_field(name="Options:", value=f"**✅ = {option1}**\n\n**❎ = {option2}**")
embed = await ctx.send(embed=embed)
await embed.add_reaction('✅')
await embed.add_reaction('❎')```
error message wont print, any ideas?
If your a beginner use replit it can be used 24/7 I suggest you seeing a video of it
I'm not a beginner. repl.it would fucking die trying to run my bot lmao
Error
Ok then
plus I need a database
discord.ext.commands.errors.MissingRequiredArgument: question is a required argument that is missing.
Replit had db
🇴
how are you running the command?
wdym
^poll "question" "opt1" "opt2"
but im trying to make an exception so when you only do "^poll" it gives you instructions on how to use the cmd
there's your issue, question needs to be optional
I tried to make an error handler but its not functioning could I have some help on it?
if isinstance(error, commands.MissingRequiredArgument):
embed_2=discord.Embed(description=f"You need to supply a subreddit. Example: <prefix>reddit <subreddit>",
timestamp=ctx.message.created_at,
color=0xff0000)
embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed.set_footer(text="Epic Bot | Discord bot |", icon_url="https://cdn.discordapp.com/embed/avatars/1.png")
await ctx.send(embed=embed_2)
return
so do an =none
where is this code?
Have you used vs code
Like i said before, it's a command error handler.
^
what would you recommend
Inside a command
My current IDE is PyCharm, what would my IDE have to do with a VPS
You check if the command is missing a required argument then make a embed explaikng how to use it.
you need to put this in a bot event for on command error. Here's my equivalent in my bot:
@bot.event
async def on_command_error(ctx, error):
error = getattr(error, "original", error)
if isinstance(error, commands.CommandNotFound):
pass
@bot.command(name="blah")
async def _blah(ctx):
#do stuff
@_blah.error
async def _blah_error(ctx,error):
if isintance(error,commands.MissingRequiredArgument):
await ctx.send("Usage: !blah")```
@slate swan
Would it only respond to this command or all commands?
all commands, if you want for a specific command you'll need to do like ritz suggested
hey Ritz, where do you host your bot? 
or is it not big enough to host proper
I host locally, not big enough yet.
ah, fair enough
Not big enough to the point where I want to pay for it.
getting a "bots cannot use this endpoint" error when tryna get mutual friends
yea yea, I'm in the state where I gotta host. Contabo worked for a bit but they've been unreliable
that's because bots unfortunately can't access mutual friends iirc.
Yeah if you want a good hosting you have to pay for it.
Would this work inside a cog?
No.
I did, they're still pretty shit for something I pay for. Though I pay way under average so that's part of it
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'isintance' is not defined
I spelled it wrong
whats the point in it being there then?
ya i corrected it
isinstance
they typo'd, it's isInstance
ohhh
to tease us?
How would I make the equivalent work inside a cog?
Why do bots have message content if discord is just gonna remove our access to it >_>
They wanna fuck with us and mess around
change bot.command to commands.command, put self in both the command and error handler.
Lmao that pinged someone
shhh
Does anyone know how I can make a Discord bot with an AI? I was doing a quick research in Machine Learning stuff and I thought to myself "You know what? I need to troll my friends with it".
👀
Welp, that's basically just giving a chatbot access to sending and reading messages
Thats the point. Honestly I'm new with Python even though i made chatbots or other programms.




