#discord-bots
1 messages · Page 451 of 1
What's kwarg
I've tried a couple but they are usually for redbot or disco bot
and i want a cog that I can just use
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
read the button structure
So if custom emojis are allowed in buttons, then i can create a very thin emoji that matches the background of discord, to align the buttons?
@kindred epoch
ig
It's hard to align buttons, they can vary from device to device.. Also once have a look at buttons in mobile lol
the text inside the buttons is the reason
also thin emoji is nothing.. discord allows emoji to take a particular area and it's almost fixed ig
hi, how do i add charge as soon as a person joins my server?
what?
take over to a new person on the server
im making a command so i can send anon messages to my staff-chat to troll my friends but the replace() does not seems to work for some reason. Any idea why?
what are the curly brackets for
f string
hm is it because the slash is an escape char?
here is the full f string
Replace the outer ' with "
what are the ` for?
if i define more than one argument it says that the argument is missing, for example here "async def example(ctx, message):" it says "message is a required argument that is missing." even though it is there
when you invoke the command in discord, you have to provide that argument
to make it look like this: hello
oh my bad, you're right
yeah but with 3 looks better for me
try ...replace(r'g/staffchat', '')
Ah must be bc I'm on mobile
yeah but I have await message.delete() ?
ok, thanks
yes
be careful when you have / in a string
wait so why wouldn't it work though? sorry to bother just curious
you didn't provide enough arguments when you invoked the command in discord
I guess that's how the font renders it
they have unicode representations I assume
theres a error that says invalid syntax where it says Optional, useful function
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
so im not allowed to make a music bot?
Please delete this message, as it contains tos breaking code 
At least not using this way
You can but we can't help you with this in the server.
okie
ok
if msg.content.startswith('!dm '):
await message.channel.send("Dming user")
dm = await message.author.create_dm()
await dm.send("What you want to send")```
it says unindent doesnt match any indentation level, for the if statement
help
@somber musk 
wut
an indentation error is the basic of the basics
if you can’t even solve that yourself, you should revisit python basics
Anyone have any idea why I keep getting this?
AttributeError: 'CommandInvokeError' object has no attribute 'channel'```
you’re probably using on_command_error which iirc ctx should be the first argument
and the second is the error
!d discord.on_command_error
discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
yeah
Ahhh I’ll have a read. Thank you
how do i create a bot?
can someone send me code to an economy bot
No, but you can code one yourself.
How Do I make the bot track server daily joins and messages?
Save the amount of messages and joins per day and get the average of it
I would do it as weeks or month
What About Day?
Average amount of joins and messages per week for month
Use datetime
!e
import datetime
print(datetime.datetime.day)
if i save a await ctx.send into a variable, is there a way i can use that var to delete that specific msg?
I have datetime but how i make the command?
await var.delete()
messagecounts = {}
@bot.command()
async def serverstats(ctx):
embed=discord.Embed(title=f"Statystyki serwera {ctx.guild.name}")
embed.add_field(name="Users:", value=ctx.guild.member_count, inline=False)
embed.add_field(name="Channels:", value=len(ctx.guild.channels), inline=False)
embed.add_field(name="Messages sent:", value=messagecounts[ctx.guild.id], inline=False)
await ctx.send(embed=embed)```
had this and it does not work
thanks
Yes,
msg = await ctx.send("hi")
await msg.delete()
thank you
Do you know how to use a database?
If you don't, then learn that first before doing all this
Because if your bot restarts all of your data is lost
The message count would be reset
Using a database is to keep storing it even if the bot dies
ok how do i get data base / learn about it?
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
Using SQL
is there an event when a channel is deleted?
Or if u want a NoSQL database use MongoDB
Alright so how ima make a data base now
Hmm.... Have you tried on_guild_channel_update
nah
like whats its about
!d discord.on_guild_channel_update
discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
i dont think it will work for it
A database is a way of storing data
Found it
!d discord.on_guild_channel_delete
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.
thanks!
import discord
import random
TOKEN = ''
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}' .format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user.message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'забавление':
if user.message.lower() == 'zdr':
await message.channel.send(f'zdr, {username}, az obicham jelqzo')
return
elif usermessage.lower() == 'kosta':
await message.channel.send(f'nishto brat, pri teb')
return
elif user.message.lower() == 'na kolko si':
response = f'az sam na {random.randrange(100)}'
await message.channel.send(response)
return
client.run(TOKEN)
it wont start
To make a mongo db database simply go on their site, create an account, make a project then a cluster, connect to it, and use the motor module to work with the database
What's the error
Yeah i am making a account rn
Wait
Making a database and managing it is part of #databases btw, although i recommend TechWithTim's tutorial on MongoDB and python, it's really helpful and easy to understand
thats the eror
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Downloads\DiscordBot\main.py", line 16, in on_message
print(f'{username}: {user.message} ({channel})')
NameError: name 'user' is not defined
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Downloads\DiscordBot\main.py", line 16, in on_message
print(f'{username}: {user.message} ({channel})')
NameError: name 'user' is not defined
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Downloads\DiscordBot\main.py", line 16, in on_message
print(f'{username}: {user.message} ({channel})')
NameError: name 'user' is not defined
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event```
Read the error again
yes...
it says user not definded
Yup
And looking over your code you haven't defined user
how to defind it xD
user = message.author
Wait
im new
Why are u doing user.message
sorry for my fooling
What's that supposed to be
i watched it on yt
idk, im new and i dont know that
I can't help you if you don't know what user.message is supposed to be
I made an account what else can i do now
Go to yt and watch python and mongodb tutorial from TechWithTim
what is wrong whit this
@bot.command()
async def poll(ctx,*,message):
emb=discord.Embed(title=" poll ", description=f"{message}")
msg=await ctx.channel.send(embed=emb)
await msg.add_reaction('👍')
await msg.add_reaction('👎')
Alright
He'll show you the basics of connecting and working with mongodb with python
Any error?
no.
Well i think user.message is supposed to be a keywoard like when you tipe zdr thats user.message
What's wrong then
??
Is any other command working
user.message is the discord message
That's message
Not user.message
To get the message's content you do message.content
im gonna show code wait.
can anyone guide me through using git
import discord
import os
from discord import embeds
from discord import message
from discord.ext import commands
bot = commands.Bot(command_prefix='?')
@bot.event
async def on_ready():
print(f'We have logged in as {bot}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
@bot.command()
async def poll(ctx,*,message):
emb=discord.Embed(title=" poll ", description=f"{message}")
msg=await ctx.channel.send(embed=emb)
await msg.add_reaction('👍')
await msg.add_reaction('👎')
so whats wrong whit it?
Bc of your on_message
what do i do to it?
Add await bot.process_commands(message) at the end of it
so
@bot.event
async def on_message(message):
await bot.process_commands(message)
like that?
@slate swan when i choose the middle one it brings me to payment
And then press?
on_message(message):
await bot.process_commands(message)
ok i pressed it and it carry me to sum else
ok.
I'm pretty sure Tim's vid is showing you how to create the account as well
"New clusters take between 1-3 minutes to provision"
Yes
Video is from to years ago and this is not in his vid
yes it works thx.
but its not reacting?
Are python bots any good?
Wdym
Yes
What can they do?
i made it react
msg=await ctx.channel.send(embed=emb)
await msg.add_reaction('👍')
await msg.add_reaction('👎')
Everything any bot can do
And the issue?
Alr.
its not doing it!
yes.
Then idk what's wrong 😔
oh yay i fixed it!
Gj
#purge command
@bot.command(pass_context=True, name="purge")
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
await ctx.message.delete()
await ctx.channel.purge(limit=limit)
await ctx.send('Successfully Cleared {} messages'.format(ctx.author.mention))```
how can i change the ` await ctx.send('Successfully Cleared {} messages'.format(ctx.author.mention))` bit to say the number that they typed in?
thanks for helping.
Just replace that ctx.author.mention with limit
just figured it out lol ty
Hey, why do pings look like this when I'm pinging a leaving member?
how do i publish a message using a bot
the member isnt in the server so it just uses their id
in what case?
Why doesn't it us their tag?
because you're mentioning them
!d discord.Message.publish
await publish()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Publishes this message to your announcement channel.
You must have the [`send_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.send_messages "discord.Permissions.send_messages") permission to do this.
If the message is not your own then the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is also needed.
i have a config cmd which takes a bit to grab items from a db, so i want to send an embed saying loading then edit it to the new embed.
async def config(self, ctx)
embed1=discord.Embed(description='**Loading...**')
msg = await ctx.send(embed1)
grab from db
blah blah
embed=discord.Embed()
embed.add_field(name='stuff from db')
await msg.edit(embed=embed)```
but it sends me <discord.embeds.Embed object at 0x000001EBC8DD1A60> as my first loading embed
nvm
never did embed=embed1 
trigger word?
*replying to the message above it
I dont think you need a decorator for that
i was using @commands.Cog.listner()
it came back as an error Cog has no attribute 'listner'
should be listener
jesus bro i can spell 💀
self, message

how would i go about making an embed that would be sent to a log channel when a command is used
!d discord.on_command
discord.on_command(ctx)```
An event that is called when a command is found and is about to be invoked.
This event is called regardless of whether the command itself succeeds via error or completes.
send the ctx.command.name
for i in data:
member = self.client.get_member(i)
print(member.name)```
`AttributeError: 'Bot' object has no attribute 'get_member'`
use get_user instead
member is a guild specific user, while user is a discord user account

how can i track daily messages?
!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.
how do i add an emoji to a status, if it is possible
I don't think you can. I'm not sure.
thats what i thought, just wanted to be sure
i think you can
custom ones? or default?
I think he meant that emoji thing.
But if he means inside the status's content, yes you can, but only default emojis.
If you're on Windows 10 you can click win + period and a small thing will pop out which you can search for emojis with.
nah, not really
How is that possible?
Wait you can.
If you give it the activity as a discord.CustomActivity.
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
`x == y` Checks if two activities are equal.
`x != y` Checks if two activities are not equal.
`hash(x)` Returns the activity’s hash.
`str(x)` Returns the custom status text.
New in version 1.3.
It has an emoji attribute.
um, how do i change my status 
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None, afk=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
no, my status 
What?
i cahnged it from mmobile
either one
Click on your avatar on bottom left.
lol
n-no

i cant.. use custom emoji in my status
?
You need nitro.
But not in the content tho. Only the emoji.
yeah
@visual island Working on a
should be itsuki-bot lol
It should be an and not a then.
Oh. 
async def on_message(message):
guild1 = client.get_guild(884150367884025897)
invites = await guild1.invites()
for invite in invites:
if invite.code == code:
pass
else:
await message.delete()``` Is my code currently, I'm trying to make it to where it deletes all invites besides for invites from a certain guild... this code currently does nothing because I'm not sure what to add in the `if invite.code == code:` area.
You will have to take code as an input from the user
Use ext.commands that will make stuff a lot more easier
Could you explain a bit further, sorry
You will have to parse the message to get the code
!d discord.ext.commands.Bot.fetch_invite you can use this to get what guild is this invite for.
await fetch_invite(url, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets an [`Invite`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Invite "discord.Invite") from a discord.gg URL or ID.
Note
If the invite is for a guild you have not joined, the guild and channel attributes of the returned [`Invite`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Invite "discord.Invite") will be [`PartialInviteGuild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.PartialInviteGuild "discord.PartialInviteGuild") and [`PartialInviteChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.PartialInviteChannel "discord.PartialInviteChannel") respectively.
so if a user uses <prefix><command-name> invite_code you will have to parse the invite_code
I see, kinda... I'm just not sure how to parse it
what do you want the prefix and the command name to be?
Does it need to be a command? I'm not sure if that'll allow me to block users from sending an invite and delete it instantly?
oh wait my bad i misread your question
you will need to parse the invite code the user sent
You can use regex
Eek, I've never used regex, this could be a challenge
import re
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|" # Could be discord.gg/
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|" # or discord.com/invite/
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|" # or discordapp.com/invite/
r"discord(?:[\.,]|dot)me|" # or discord.me
r"discord(?:[\.,]|dot)li|" # or discord.li
r"discord(?:[\.,]|dot)io" # or discord.io.
r")(?:[\/]|slash)" # / or 'slash'
r"([a-zA-Z0-9\-]+)", # the invite code itself
flags=re.IGNORECASE
)```
Oh wonderful! py for invite in invites: if What would I place here then?
@visual island did i already ask u how i could make an error handle for this
no
i am now
yes
codes = INVITE_RE.findall(message.content) this will return a list of invite codes if it is in the message
its happens when a command is used with member @ but no reason
@client.event
async def on_message(message):
guild1 = client.get_guild(884150367884025897)
invites = await guild1.invites()
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in invites:
if invite.code == codes:
return
else:
await message.delete()``` Would be everything, unless I'm missing something, right?
Yeah, that's definitely broken 😂 It's trying to spam delete the message- no bypass either at this time
You will have to do py guild_invites = tuple(map(lambda i: i.code, await guild1.invites())) for invite in codes: if invite not in guild_invites: await message.delete()
That should work
It does, thank you so much
👍
@client.event
async def on_message(message):
guild1 = client.get_guild(764574130863079424)
invites = await guild1.invites()
guild_invites = tuple(map(lambda i: i.code, await guild1.invites()))
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in codes:
if invite not in guild_invites:
await message.delete()
await client.process_commands(message)``` One last thing, is there any possibility that I can make it "whitelist" certain guild id's invites if the bot isn't in the server?
you will have to store the whitelisted guild ids
guild1 = client.get_guild(764574130863079424) is a whitelisted guild id
is that the only whitelisted guild?
For now, yes - I'll add more eventually
!d discord.utils.resolve_invite exists as well
discord.utils.resolve_invite(invite)```
Resolves an invite from a [`Invite`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Invite "discord.Invite"), URL or code.
No real need to write all this regex yourself
then you will have to check if the invites guild id the user sent is in the whitelist
Hmmm, using resolve_invite?
to get the guild id the invite leads to you will have to use client.fetch_invite
pp = await client.fetch_invite(guild1)``` Okay, so this
What's the if statement determining if it's from that guild though?
you will have to do something like py for invite in codes: guild_id = (await bot.fetch_invite(invite)).id if guild_id not in whitelist: await message.delete()
here whitelist will be an iterable containing the whitelisted guild ids
Why not check if guild id not in Whitelist first 
first
codes is a list
AttributeError: 'NoneType' object has no attribute 'invites'``` Error
@client.event
async def on_message(message):
guild1 = client.get_guild(764574130863079424)
invites = await guild1.invites()
pp = await client.fetch_invite(guild1)
whitelist = '764574130863079424'
guild_invites = tuple(map(lambda i: i.code, await guild1.invites()))
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in codes:
guild_id = (await client.fetch_invite(invite)).id
if guild_id not in whitelist:
await message.delete()
await client.process_commands(message)``` Unless I'm doing it wrong
wrong id prob
guild1 is None
whitelist needs to be an iterable containing integers, and you can remove guild_invites = tuple(map(lambda i: i.code, await guild1.invites()))
How could I make this iterable, I'm a bit confused on this, so sorry. Interable containing integers is confusing me 😂
whitelist = (764574130863079424,)
Ahh, that makes a lot more sense
invites = await guild1.invites()
AttributeError: 'NoneType' object has no attribute 'invites'``````py
@client.event
async def on_message(message):
guild1 = client.get_guild(764574130863079424)
invites = await guild1.invites()
pp = await client.fetch_invite(guild1)
whitelist = (764574130863079424)
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in codes:
guild_id = (await client.fetch_invite(invite)).id
if guild_id not in whitelist:
await message.delete()
await client.process_commands(message)```
Hmmm, I think we have the order of the for loop wrong
remove that line
Right, right, I'm stupid 😂
@client.event
async def on_message(message):
guild1 = client.get_guild(884150367884025897)
whitelist = [884150367884025897]
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in codes:
guild_id = (await client.fetch_invite(invite)).id
if guild_id not in whitelist:
await message.delete()
await client.process_commands(message)``` Now this is removing all the invites even the whitelisted server ones
No error ^^
Try printing guild_id

It prints test if I used discord.gg/test
If I use an invite from the whitelisted server, it still deletes it and says the invite code I used
^^ (sorry if you don't want a ping, just lemme know!)
(await client.fetch_invite(invite))
This returns an Invite object
not a Guild object, so you need to get the guild with invite.guild
Could you explain a bit further, please?
(await client.fetch_invite(invite)) is not a guild
Doing .id doesn't return the guild ID
However you can get the guild with (await client.fetch_invite(invite)).guild
@client.event
async def on_message(message):
guild1 = client.get_guild(884150367884025897)
whitelist = [884150367884025897]
INVITE_RE = re.compile(
r"(?:discord(?:[\.,]|dot)gg|"
r"discord(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discordapp(?:[\.,]|dot)com(?:\/|slash)invite|"
r"discord(?:[\.,]|dot)me|"
r"discord(?:[\.,]|dot)li|"
r"discord(?:[\.,]|dot)io"
r")(?:[\/]|slash)"
r"([a-zA-Z0-9\-]+)",
flags=re.IGNORECASE
)
codes = INVITE_RE.findall(message.content)
for invite in codes:
guild_id = (await client.fetch_invite(invite)).guild
if guild_id not in whitelist:
await message.delete()
await client.process_commands(message)``` This still deletes all of the invite codes, so sorry if I read it wrong
guild_id would be a discord.Guild object, not an ID
So that doesn't work
Try to figure out how to make it work on your own
Isn't guild_id the thing that you said that it would work with, no?
I didn't say that it is going to be the guild id
guild_id = (await client.fetch_invite(invite)).guild this, not like the actual guild_id
oh yeah mb
Yes it's not an ID
try printing it out
Ah, true
To see what it actually is
The hecc, it prints TEST Squadron with discord.gg/test very weird
OH! That's the guild name wait
guild_id = getattr((await client.fetch_invite(invite)).guild, "id", None)
how can I overwrite a cog or command?
Oh my, thank you so much, Rush!
Why spoonfeed smh
how do i make a command cooldown
Is it possible for a steal emoji command?
!d discord.ext.commands.cooldown
discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") and the local error handler.
A command can only have a single cooldown.
👍
ty
for like a leveling system how would i set it up like do i just add the user and the guildto the database
and in on_message add +1 to the point for the user in the database,
and after that i check if t he user reached the specific number send an level up message
is this wrong ? i came up with this just right now
Its good
You can also check if the user is spamming for more precision
or add exp randomly
anyone wanna collab in my bots rewrite?
if i get paid, yes 
i have no budget xd
looool
its a fun project that id maintain for long i think
itll be my only bot
what are you trying to do ?
my english is bad so i don't know what that word kidna means
but yeah since almost everything needs rewrite id do it
are you rewriting because of slash commands ?
money bot
kindof, my commands are buggy too
so id rewrite over all of them again
into a new one
use edpy 2.0 gnome fork branch
nah id stay discord.py for now, im just looking for a collaborator
it has slash commands, its written so that it turn the normal commands to slash commands
and you have both slash and normal commands, edpy is dpy but forked
so do you wanna collab?
just a person that helps me rewriting it
ill also give you the github repo of the old bot
its messy trust me
i have a bot myself,
whats the repo?
its private rn
my problem right now with you is like, i don't know how to do economy stuff, you need you explain and give me the idea, and how you want it
sorry if that was rude
nah it wasnt
so id use mongodb for the data (user data) and json files for the rest of the stuff that is long
idk how to describe
no idea
but i use json for it
idfk man :(
i don't know mongodb, cause i heard it's kinda bad for json stuff, i prefer postgresql, and by explaining, i mean like explain the commands
i have no budget for hosting postgresql and my pc has no space for self hosting postgresql
you don't need to pay ?
wdym space ?
you don't need storage for postgresql server i think
thatd be good but i dont really think so, its too good to believe lol
free, no storing on pc, too good to believe
what do you think mongodb does ? :/
uhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
btw im in online class rn sorry
dm me if u wanna collab
ok
i can code in afternoon (like 3 to 5 hours later)
me myself might make some economy commands as well
i will explain the postgresql to you as well
8:34 am 🤣
ooh
but i'm awake till 6:00 pm
not far away
i don't sleep at that time
but you said it
What do I need to install to configure the bot?
just do pip install discord.py it would install it's dependecies as well
i can't write that word 
How to get resent message.content from a channel by name
wdym by name ?
Channel name
so like <channel's name> - <message.content> ?
Channel name fixed need to get message.content and store it as a variable
do await ctx.send(F"{ctx.channel.name} - {ctx.message.content}") i think
@oak quest
no need to ping i answered you already
"pip" is not recognized as an internal or external command,
executable program or batch file.
What do you do? 
do you know python ?
have you ever installed any packages ?
But it is not correct need to store message.content from a channel and make it as variable and process it
are you making a command or you are doing it on_message ?
Ok
no, so i asked what should i install
than first learn python and pip
See the code I had done so far
@client.event
async def on_message(message):
if message.channel.name == "to rmb":
messages = await channel.history(limit=1).flatten print(messages)
```
@oak quest
DON"T PING ME
Ok
and this is an event not command
Is it correct
i don't know wtf is this await channel.history(limit=1).flatten print(messages)
See channel history for messages when set to 1 will bring resent message
use channel.last_message to get the last message
Ok
i think the problem is channel
do channel message.channel ?
@client.event
async def on_message(message):
if message.channel.name == "to rmb":
messages = channel.last_message
print(messages)```
This code not working
what is the error
No error no response
do message.channel
Whre
Channel not defined error
where do you think you should do that
Want to get recent message from channel to-rmb and print
Look at the code and check if you defined channel
i thought discord.py was discontinued i switched to js lmfao
Defined by line 3 is it not
it is
oh
use forks
how?
if you don't want to switch to js
i thought nobody wanted to maintain it though
you never did channel = so how did you define channel?
use edpy cause they even have slash commadns
theyre forks?
fork are different than that
If message.channel.name == "to-rmb"
DUDE
@spring flax
okay and?
WHERE DO YOU THINK YOU DIDN"T DEFINE CHANNEL
it's easy python
people can't just spoonfeed you
learn python first than dpy
his code is an event not a command
!resources @slate swan
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yh ik but why tho
you don't have ctx in an on_message event
@client.command
async def command(argument):
print(argument)
cant you do this
ohhh wait
wait
wait yeah he can
okay well no that is not what he wants
he's doing event not command,
well what is he trying to do
and that is missing ctx param
yh ik i switched so kinda weird
Trying to get message.content from a channel
like printing the content of every message sent in a channel?
dude
you still haven't seen it ?
@client.event
async def on_message(message):
if message.channel.name == "to rmb":
messages = channel.last_message
print(messages)```
error = channel not defined
ooh
what do you guys think is the problem ?
dude it's right there @slate swan
message.channel.last_message
bruh, he needs to get to know that himself
i'm back
how do I make a bot send a dm to a user who joins the server
Omg tys?!
on_member_join
and
await ctx.user.send
Which library do you use for discord bot
tyy
py
Does it maintain by discord team?
ohh mb
Where select bot?
o ok
@tawdry perch i enable all :)
OMG TYSSM
TYSM
I GOT IT
@tawdry perch
Im using python
Can you teach me
Or give me
A code to
you should select Chọn máy chủ 😄
Do the command
'(
If user send !rickroll
My bot do a rickroll gif
Can you give me code to do it?
I didnt learn discord.py
Cuz it discontinue
what did u learn then
I only know some
Do you have any knowledge of python? It's pretty simple of what you're trying to do
Ex: @client.event
@bot.event
...
Learn basic python before trying to create a discord bot :)
outdated code
eh ig
should i use heroku's postgresql? just wanna know if there are any limits or bad things before i start using it
heroku is bad for hosting
if coucil or creator in interaction.user.roles: how can I make it check if the user has either one of those roles? Right now it requires the user to have both.
but you can still create a simple dsc bot with the current ver of dsc.py
true
:(
what have you made in python @tawdry perch
like what kinda bots
im rewriting my economy bot to js :p i am a noob xd
nodejs?



. If you could help me out I would really appreciate it :)
interaction.user.roles returns a list of roles right
I believe so
so you just do the normal way
if something in list and the other thing in list:
pretty sure theres no shortcut
It's still safe to use discord.py
theres probably gonna be a decent fork
It hasnt been taken down, and there are maintained forks
theres already a fork that im looking forward too and it kind of works lol
This would make it require the user to have both roles
I just need the user to have one
I was a project lead for a while
or
instead of and
is this for command permissions?
discord.py/derivatives have a decorator to check for roles
Still requires both
It's for a button
ahh
class TicketClose(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(emoji='🔒', style=discord.ButtonStyle.gray, custom_id='ticketclose')
async def ticketclose(self, button: discord.ui.Button, interaction: discord.Interaction):
coucil = discord.utils.get(interaction.guild.roles,name='The Coucil')
creator = discord.utils.get(interaction.guild.roles,name='The Creator')
if coucil in interaction.user.roles or creator in interaction.user.roles:```
huh did you rerun your bot
Yep
then idk cause it looks fine to me
ouch
Well, for me. I am moving to disnake haha
i kinda feel bad tbh
Haha, I am aswell.
Cool :D
I'm tempted to set up some sort of discord bot hosting service
i thought alot of the discord.py people switched to d.js but ig not
Hmm
and free for all the people who help in this channel
It might be an error with buttons then?
im pretty sure you didnt rerun your code or something like that
you can have 25% of a core and 256MB of ram for free 
totally not me
is it limited like heroku though (time limits or whatever)
Sure. Just increase it to 300 MB and I am more than happy :D
I spelt something wrong aha
it doesnt exist yet
I wonder if you can connect to discord via IPv6
last i remember discord still wasnt using ipv6 which is annoying
vcokltfre@antares ~ $ dig -6 discord.com
; <<>> DiG 9.16.1-Ubuntu <<>> -6 discord.com
;; global options: +cmd
;; connection timed out; no servers could be reached
```pain
Is there a way to get the first message ever in a specific channel?
modmail...?
yes, await channel.history(oldest_first=True, limit=1).flatten()
you go on the website, buy a subscription, and voila hosted modmail
with your own log viewer/etc.
add the premium pateron features?
Alec becoming the next millionaire
what?
message.channel
idk what i said me too
for an users id, will i use a row or a column? i cant differ these 2
so if i get a 10k rows limit will i be able to store 10k users or something
I've been learning CSS, so my plan is to as closely as possible recreate discord messages in the browser for logs
@discord.ui.button(emoji='🔒', style=discord.ButtonStyle.gray, custom_id='ticketclose')
async def ticketclose(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.channel.history(oldest_first=True, limit=1).flatten()``` Okay so, how could I filter out the mention and get the mentioned user's ID using the `channel.history(oldest_first)`?
Here's a video showing what I want it to get
I think instead of relying on channel message history you should look into storing that data in some persistent storage like postgres
doesnt work for me either
Ehh, I would have to rewrite hundreds of lines of code because I need to store the channel id too
I think the history would work best in this instance
Would it be possible to do what I'm trying to do though?
yes
Hunter who uses his server's text channel as database 👀
I did that only once 👀
How could I yoink the mentioned user's ID out of the message then?
!d discord.Message.mentions ?
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
A database?
How could I use this with the await interaction.channel.history(oldest_first=True, limit=1).flatten() code?
Sorry, just I don't see any way of using it 😅
It returns a list of Messages. You gotta loop through them
that returns a list of messages i believe, so get first object, and use that
Hmmm- super confused. I'll try a few things though :)
Look, that code u r using... It returns the list of discord.Message objects... So you can loop over the list and check for message.mentions
await interaction.channel.history(oldest_first=True, limit=1).flatten() returns a list of discord.Message like [Message1, Message2, ...]
Since you are only requesting one, it'll be like [Message], index it to 0 to get the first message object.
Then use .mentions on it, which will again return a List of Member/User objects, like [Member1, Member2], and index it again
Oh jeez, that made my brain even more confused 😂

Haha
Look @hollow agate, I know sometimes it can be too much. You should think about it yourself
xD yeah for sure, I'm gonna try to break it down
So, what is index used for? I've rarely used it and I don't understand what it'll do in this instance.
getting an item in a list
Why not last_message?
so if we have ```py
somelist = [1, 2, 3]
as lists start from 0, the first (1) will have an index of 0, 2 will be 1 and so on
Can I make a command in which only a certain person can use it?
yeah, just check id. if its invalid, return
oldest_first=True
interaction.mentions[0].id is a start?
Oh
author = interaction.mentions[0].id possibly maybe unless I'm not understanding it
Is there a get_category method?
no
And where do I enter the id? 
how to check if nick already exists in ctx.guild?
Damn.
you can pass in the category id into get_channel
get_channel can also get category
@slash.slash(description='to change nickname')
async def changenick(ctx: SlashContext, member: Member, *, nick):
embed = mbed(
description=f"**Information :**\n```\nAuthor : {ctx.author}\nUser : {member}\nNickname : {nick}```", color=ctx.author.colour,)
embed.set_author(name=f'Change Username',
icon_url=str(member.avatar_url))
embed.set_footer(text=f'command used by : {ctx.author}',
icon_url=str(ctx.author.avatar_url))
if nick == member.display_name:
await ctx.send('username must different')
else:
try:
if ctx.author.guild_permissions.administrator:
user_nick = ctx.guild.members
if nick in user_nick.nick:
await ctx.send('nick already exists')
return
await member.edit(nick=nick)
await ctx.send(embed=embed)
else:
await ctx.send('you are missing permissions')
except discord.errors.Forbidden:
await ctx.send(f'{ctx.author.mention}, @hallow urchin missing permissions')
except Exception as e:
print(e)
await ctx.send(e)
e = sys.exc_info()
print(e)```
i dont use interactions, so i wouldnt know what that does
Ahhhh, Thanks to you both!
Basically just message.mention[0].id
interaction.mentions does not exist iirc
if ctx.message.id != idofpersonallowed:
return
its terrible, and there is probably a better way of doing it
Yep, it doesn't lol
nice, what is it?
how to check if nick already exists in ctx.guild?
my code
Oh, thanks
maybe looping through members, and checking the nickname (if they have one), and if so, stop and do something else
very nice
Suggest more topics here!
I'll return to my issue later, my brain hurts 😂
like this? cs members = ctx.guild.members for member in members: .....
Better
How to grow my AI Bot
for member in ctx.guild.members:
if member.nick == "nickname here":
...
return
something like this
maybe
members = ctx.guild.members
for user_nick in members:
if user_nick.display_name == nick:
await ctx.send('nick already exists')
return
await member.edit(nick=nick)
await ctx.send(embed=embed)```??
A Cyborg
.nick or .display_name?
.nick
okey i try
!d discord.Member.nick
The guild specific nickname of the user.
for any of you who doesnt know how to code an unban command found this online. tested and works
@bot.command(name='unban')
@commands.has_permissions(ban_members = True)
async def unban(ctx, id: int):
user = await bot.fetch_user(id)
await ctx.guild.unban(user)
could replace name='unban' with aliases if need be
A better way would be making a discord.Object instead, saves an API call
now i want to code it so the bot sends a messages when soemone has been baned
but idk how
!d discord.on_member_ban
discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
intents = discord.Intents.default()
this a good placeholder?
thank you, work
is it bad to use Intents.all()?
Depends, it consumes more memory if you have all enabled
If you don't need any intent, just disable it
Especially Presence Intent
it takes a lot of memory and most of the time you don't need it
its best to use intents that you are going to use only, it would use memory like Akshu said but also you would be receiving unnecessary information
Presence intent and presence are different things
Intent allows the gateway to receive others presence data too
@bot.command()
async def funhelp(ctx):
channel = ctx.message.channel
embed = discord.Embed(
title = 'Economy bot commands do ~help',
colour = discord.Color.blue()
)
embed.set_thumbnail(url= r'https://i.pinimg.com/originals/65/b1/ef/65b1ef4ae4a802082e0956e7848e953b.gif')
embed.set_author(name= f"You have done .funhelp")
embed.add_field(name='Fun Commands', value= '.dailyastronomy, .hug, .kiss, .slap, .spit, .coinflip, .fortune', inline=True)
embed.add_field(name='Important Commands', value= '.version, .funhelp, .welcome', inline=True)
embed.add_field(name='Custom Commsands', value='.w, .l, .f, .taco, .cringe, .fish, .ayoo, .gay', inline=True)
embed.add_field(name='Economy', value='.balance, .deposit, .get, .send, .slots, .shop, .sell, .buy, .rob, .beg', inline=True)
embed.add_field(name='Moderation', value= 'MODS ONLY: Do .modhelp', inline=True)
await ctx.send(embed=embed)
Worked jsut fine before i added the last field
visable confuusion
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.
👀 #rules
💀
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
bruh
why do i get this error
<@&831776746206265384>

welp was going to double ping
Lol
oh wow im so scared 💀
bruh
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
em = discord.Embed(title=f"Error!!!", description=f"Command not found. Try using **.cmds**", color=ctx.author.colour)
await ctx.send(embed=em)``` what do i add so that it deletes the message which includes the non existing command
diabolical is alive
ummmm
skid lol
await ctx.message.delete()
!ban 784074403871719484 Racism
:incoming_envelope: :ok_hand: applied ban to @drifting venture permanently.

Thanks :D
so i have a command where each time someone runs it it increases by 1
genios
very lovely
e.g. i run !hi and the bot will say cmd ran by 1 person and when another person does the command bot would add on by one and say cmd ran by 2 people
and when my bot restarts it wont reset the count
save the count in a db
i dont have a db + its just a bot for 1 server
Use a local db like sqlite

Is there a help channel dedicated to docker related stuff? 
help channel?
ik but i dont wanna use a db for such a small bot
could i use json i know it aint good but could i
What's devops
nvm off topic
why not?, sqlite is petty simple
you can do that
but JSON wont scale
hm
Scaling is the process of increasing or decreasing the capacity of the system by changing the number of processes available to service requests
I used to feel this way, but I've come to realise that if I use databases for everything it's easier to work with then when I need to, and it's consistent across projects so I don't need to think as much and can use existing tools to do things
How much does a database cost nowadays? For like 1 guild with a couple thousand members
free
Yeah, my database has about ~550k user records and uses about 200MB of disk space and 0.1% CPU, so given the server cost $5 a month... basically zero
Is using redis in a discord bot any good? Like I don't think a bot needs so fast handling of cache.. 
Any advantage of using it?
Should be enough, also apply constraints like NOT NULL to prevent improper data
and maybe a unique constraint also
Unique is.. I don't think their model can have anything in unique
Like with 1 guild id, there can be multiple tickets
isnt the channel supposed to be unique?
Uh what's channel_id btw?
Dms are itself channels in modmail 
Oh okay
Yes it'll be unique
make a custom check or use @commands.has_permissions/@commands.has_guild_permissions
!d discord.ext.commands.has_permissions
discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
@client.command()
async def modcmds(ctx):
if (ctx.author.guild_permissions.view_audit_log):
embed = discord.Embed(
title = '',
description = '',
colour = ctx.author.colour
)
embed.set_footer(text='By oSeatch#6969')
embed.set_author(name=ctx.message.author)
embed.add_field(name='Mod Commands', value='__mute__ , __kick__ , __ban__ , __unmute__ , __purge__', inline=False)
await ctx.send(embed=embed)
elif (not ctx.author.guild_permissions_view_audit_log):
await ctx.send("This command requires a higher rank!")``` eh i tried this but the elif breaks
anyone know what im doing wrong at elif?
@client.command(administrator = True)
async def ticketsetupp(ctx, *, message):
if message is None:
return await ctx.send("please add a description for your ticket")
tick = discord.Embed(title= f"{ctx.guild.name}", description = message, color = 0x01BDFE)``` can anyone help me ? the if messsage doesnt work
guild_permissions.view_audit_logs
yea thats correct though
still can you help
what?
mobile sucks and my brain too
the syntax seems right to me
can anyone help me with this
if i remove the elif, it works, it doesn't show the msg
its ctx.author.guild_permissions.view_audit_logs
it’s throwing AttributeErrror
still not working
@bot.command()
async def invite(ctx):
embed = discord.embeds(color=0x2983c7,)
embed.add_field(name="INVITE:", value="[click here to invite the bot:](https://discord.com/api/oauth2/authorize?client_id=)")
await ctx.send(embed=embed)```
what is "not working"
it just shows an error
module is not callable
ok then send the error?
discord.Embed
._.
same as before
im dumb lol
!indent
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
i still dont get whats wrong in it..
reload your window
if i remove this
elif (not ctx.guild.permissions.view_audit_logs):
await ctx.send("This command requires a higher rank")``` it gets fixed
why are you using those parenthesis after elif
I want to make an API request right after the bot logs in, any idea how?
discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready") for that.
The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready "discord.on_ready") also apply.
you can override start and do it inside of there
i think you don't have to use them in python
elif condition:
not
elif (condition):
Do commands.Group follows same structure as commands.Command since it inherits from the latter..
Can I use same kwargs as I do in a command?
yes afaik
Since a lot of them are missing in the docs in the group but is there in command
Ah yes docs have this mentioned too, didn't notice
Im trying to do banned words system with .db.
How do i check the words
My code:
banned_words = await self.db.execute("Select Count(*) from blwords guild_id=? and words = ?", (guild_id, words))
reindent that line
Isn't it blocking?
code?
if you make an async request it isnt
meh i gave up lmao
i mean if u dont have the perm, it doesnt show the msg, i just wanted to make it so that if u dont have perm it shows that you need a higher rank
Oh stupid me thought about bot.connect
Like to subclass Bot and all that
on_connect can be called only once per-session right? Unlike on_ready
Hello, is there a way to ban members who are already in a guild with less than 5 days old? this is my code but it keeps on giving me error "ban() missing 1 required positional argument: 'member'"
code:
@tasks.loop(seconds=5)
async def ban(member):
for member in client.guilds:
created_at = (datetime.datetime.now() - member.created_at)
created_at = (datetime.datetime.now() - datetime.timedelta(days=5))
if created_at < days:
await member.send("You were banned for being a possible raider, if that is not the case please join the ban appeal server: ")
await member.ban(reason="Possibly a raider account age is {} days old".format(str(created_at)))```
discord.Member right?
wdym?
oh yikes
It's giving the error because you're not filling the member param with anything
And why would you loop when you could just do it when they join the server
its because someone can already be in the server as a raider so its to remove that
Show where you are calling the loop
Then just do a command instead of a loop and move to on_member_join so you ban them when they join
oh yeah I did not think of that lol thanks
Also you didn't define what days is so you'll have another error
And you redefined created_at so it won't be the member's creation date that you'll be comparing
ratelimits
can i make this better ?
quote = get_quote()
await message.channel.send('Hello')```
yes, make it a command
how to ?
can u tell
#some imports
import discord
from discord.ext import commands
@bot.command(name="name here if you want a different one than the function name", description="describe it here", hidden=False) #set hidden to True to hide it in the help
async def mycommand(ctx, argument1, argument2):
'''A longer description of the command
Usage example:
!mycommand hi 1
'''
await ctx.send(f"Got {argument1} and {argument2}")```
Example
ok thanku
How can i make my bot online
run the bot
🤣
!d discord.ext.commands.Bot.run
run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").
Roughly Equivalent to...
^
if i do the command to add words, only the first word i add to the db is working
Yes. I have a command for it
look
i guess the on_message eventt
yea
@commands.Cog.listener()
async def on_message(self, msg):
rows = await self.db.execute("SELECT words FROM blwords WHERE ? = guild_id", (msg.guild.id,))
data = await rows.fetchone()
for word in data:
if word in msg.content:
await msg.delete()
await msg.channel.send("Stop swearing!")
@commands.command(aliases=["addblwords"])
@chp(administrator=True)
async def addblacklistwords(self, ctx, *, word = None):
if word is None:
await ctx.send("Please provide a word")
return
await self.db.execute("INSERT INTO blwords (guild_id, words) VALUES (?, ?)", (ctx.guild.id, word))
await ctx.send(f"The word {word} added to blacklist")
await self.db.commit()
the command
thats the problem
im getting error
Traceback (most recent call last):
File "C:\Users\eyal2\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "c:\Users\eyal2\OneDrive\Desktop\Python\Bot\bl\system.py", line 42, in on_message
if word in msg.content:
TypeError: 'in <string>' requires string as left operand, not tuple
Um
Oh
Ok
if msg.content in word?
repost your error please
you mean the other way around? because that sounds more logical
could you share your code?
!paste if it's too long
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.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.




?

