#discord-bots
1 messages · Page 272 of 1

discord.app_commands.errors.CommandInvokeError: Command 'rec' raised an exception: AttributeError: 'Interaction' object has no attribute 'defer'
probably interaction.response.defer()
well i got the output but bot still thinkin
releasing & destroying might take a while?
it waits only 5 seconds after releasing, but hes still in a deep thoughts
no idea what you mean by that
small rewrite note
await find_channel("💻-screen").send(file=discord.File(output_file))
embed = discord.Embed(title="Recording has been made!",
description=f"Check it out at <#{find_channel_id('💻-screen')}>",```
---
```py
channel = await find_channel("💻-screen")
await channel.send(file=discord.File(output_file))
embed = discord.Embed(title="Recording has been made!",
description=f"Check it out at {channel.mention}",```
oh thanks
current code?
yes, btw print after removing the file is working
even better rewrite:
# no sending of file in a separate message anymore
# ... send(file=...)
embed = discord.Embed(title="Recording has been made!",
description=f"Check it out at {channel.mention}",
colour=embed_color,
timestamp=datetime.now())
embed.set_footer(text="SnoopRat",
icon_url=SnoopRat_icon)
# file gets sent together with embed
await interaction.followup.send_message(file=discord.File(output_file), embed=embed)
you do realize that probably while your screen is recording, that you're blocking your bot from doing other things because the video writer writes sync instead of async?

try any other command WHILE your bot is recording, you'll see
yeah ik, so how do i fix it then
btw heres the console output now RuntimeWarning: Enable tracemalloc to get the object allocation traceback
you read the wrong line of code
you're not awaiting a certain line
you should use an async writer in order to prevent your code from being blocking
OR you should run it as a task...
I opt the former
ok then, thanks for help
gl hf
can someone help me with discord bot im almost done just have 1 problem dm me,
hey sir u free?
need some help
https://discord.com/channels/267624335836053506/1131066844623675493
i have posted my issue can someone help me pls
still having an issue?
no i fixed thanks doe
can anyone help me with that error on replit please :
It is what it tells you
There is no package libs.solver
Is anyone experienced with hypixel api im trying to make a bot that needs to get allthe stats and stuff for an account
When i try to use it it does this
Gets none of the account stats/info
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
can you send the json response of the API
Liek what it says in terminal on VSC?
def get_player_data(username):
url = f"https://api.hypixel.net/player?key={api_key}&name={username}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
if data.get('success'):
return data['player']
return None
(also, requests is blocking, use an asynchronous library instead)
import discord
from discord.ext import commands
import os
intents= discord.Intents.all()
bot = discord.ext.commands.Bot("!", intents=intents)
Token = os.environ['token']
@bot.event
async def on_ready():
print("Bot Online")
@bot.event
async def on_member_join(member):
join_channel_id = 1028256485383344170
join_channel = bot.get_channel(join_channel_id)
member = str(member.mention)
await join_channel.send(member + " is here")
@bot.event
async def on_member_remove(member):
leave_channel_id = 1028256485383344170
leave_channel = bot.get_channel(leave_channel_id)
member = str(member.mention)
await leave_channel.send('GoodBuy ' + member)
@bot.command(pass_contaxt = True)
async def joinme(ctx):
if (ctx.author.voice):
voice_channel = ctx.message.author.voice.channel
await voice_channel.connect()
bot.run(Token)
this shows when I type
!joineme
Hello?
@slate swan
....
Please anyone help me
poetry add discord.py[voice]
import?
Run in shell
It's repl it
Ok I will try
And yeah if possible switch to desktop, it's heaven compared to mobile coding
I don't have pc
Can you give me how to type it exactly?
That is exactly how you type it
Ight try pip install discord.py[voice]
Replit is screwed, on mobile it's screwed even more
Still the same error @vale wing
pip install pynacl
import discord
from discord.ext import commands
import os
intents= discord.Intents.all()
bot = discord.ext.commands.Bot("!", intents=intents)
Token = os.environ['token']
@bot.event
async def on_ready():
print("Bot Online")
@bot.event
async def on_member_join(member):
join_channel_id = 1028256485383344170
join_channel = bot.get_channel(join_channel_id)
member = str(member.mention)
await join_channel.send(member + " is here")
@bot.event
async def on_member_remove(member):
leave_channel_id = 1028256485383344170
leave_channel = bot.get_channel(leave_channel_id)
member = str(member.mention)
await leave_channel.send('GoodBuy ' + member)
@bot.command(pass_contaxt = True)
async def joinme(ctx):
if (ctx.author.voice):
voice_channel = ctx.message.author.voice.channel
await voice_channel.connect()
await ctx.send("Ok")
else:
ctx.send("You aren't in voice channel")
@bot.command(pass_contaxt = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect
await ctx.send("I left the voice channel")
else:
await ctx.send("I'm not in voice channel")
bot.run(Token)
When
!leave
I tried to remove await
But it didn't work
No errors but the command not joining the channel
Call the method to get the coroutine
await ins.meth ❌
await ins.meth() ✅
await ctx.guild.voice_client.disconnect()
Like this?
Yes?
That will fix?
No it will help troubleshoot
from discord.ext import has_premissions, MissingPermissons
What did it mean wrong location?
Both (has_premissions and MissingPermissons) don't exist in discord.ext
Can you give me what i should replace this with?
No, i can't 
mayi?
he should get it by himself :p
Also you have a typo MissingPermissons -> MissingPermissions
Then what i have to do ,
?
import requests
import discord
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from PIL import Image
from discord import app_commands
MY_GUILD = discord.Object(id=1121927606154043498)
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.default()
client = MyClient(intents=intents)
@app_commands.describe(
ip='The IP you wish to locate',
)
async def locates(interaction: discord.Interaction, ip: str):
await interaction.response.defer(ephemeral=True, thinking=True)
try:
if interaction and interaction.message and interaction.message.channel:
if interaction.message.channel.type == discord.ChannelType.private:
await interaction.send('My apologies, but you cannot use this command in private messages.')
else:
ip_url = f"https://tools.keycdn.com/geo.json?host={IP}"
headers = {
"User-Agent": "keycdn-tools:https://beta.octosniff.net/"
}
ip_response = requests.get(ip_url, headers=headers)
data = ip_response.json()
# Extract the required information
city = data['data']['geo']['city']
state = data['data']['geo']['region_name']
country = data['data']['geo']['country_name']
# Print the city, state, and country
await interaction.user.send(f"{IP} is located in {city}, {state}, {country}")
except:
print("Fucked")
The slash commands are not showing up in my discord
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Don't try to install a package that doesn't exist?
But how i can launch the script if the modules aren’t installed ?

What modules
TypeError: unknown parameter given: item
@thin raft
Hi
Yes
lanqu nice name
Oh thanks
python turtle
Used ob my script..
U also got a nice name PranavDEV
tnks
Do u need help with anything?
Cuz Yk this is for discord bots
are you ai
What no
kidding
Why did u ask that..
joke
pk do you know chatGPT
Yes
so you are developing discord bots with python
Yes
pip install module1 module2 ... thats how you install modules you need
where are you from
There is a whole discord server for that
Sorry will not say
itz okkkkie
with converstaions move to dms or #python-discussion
Ye sorry
👍
i want some frnds to lrn py
I write this command in cmd ? And it will install all modules i want automatically ?
so tring to mke frnds
Let’s move to #python-discussion
yes
ok
Thanks 🫂
i am a big developer in python i know print(''lanqu') only🙃
your friend went to #python-discussion go chat here as well
its a fresh token i dont think anyone cares enough to steal it lol
Ppl would
and someone nuked my discord
Btw that would still be wrong
great
i changed it
When
right when u said it
anyways are u able to help me w my code?
So u gave ppl access to ur bot for 1 hr
Indeed
Don’t think so
nuked 4 minutes ago though
No wonder someone nuked ur discord
What did they do?
?
the person that nuked
I got about same
Ok lol
o
i just sell a bunch of bots that help ppl pull fn accounts
lol
fortnite
Oh nvm lol
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Not malicious or illegal
He wasn’t tho
depends what you mean by pull fortnite accounts
its like a fortnite tracker
like see someones matches and stuff
- he wasn’t asking for help
yh
mhm oky
that was a discord bot
That was for a different bot
The rule says not to ask for help for the illegal bot etc
that was a bad gif
His code
ty @vocal laurel
Np
whats wrong with it?
TypeError: unknown parameter given: item
full traceback
lost it
running 1 sec
Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Ultimate\ULTIMATE.py", line 32, in <module>
async def locateip(interaction: discord.Interaction, ip: str):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 887, in decorator
command = Command(
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 666, in init
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.globals)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 389, in _extract_parameters_from_callback
_populate_descriptions(result, descriptions)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 277, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: item
Your command has only ip parameter
a command to track down ip?
And you are describing some others
I am trying to have 2 diferent commands
this is solution
There are 2 commands
one is mentioned later
so describe the other one
it is
no the second one is not even a command
you are missing decorators here
wdym
if you want to define a command you decorate a function with @client.tree.command() in this case
you only do it for one function
hence you have one command
so how do I add a second command?
if you want to define a command you decorate a function with @client.tree.command()
im new idk what that means
can u show me an example?
but you already did this?
gpt
lol
..
you need at least python basics to create a discord bot gpt is not enough
ik basics
by basics i mean decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
• Corey Schafer's video on decorators
• Real python article
can u give me an example of what it would look like to add a second command?
@client.tree.command()
@app_commands.describe(...)
async def first_command(interaction, ...):
...
you do this for each command
so I add lines 1 and 2 before every command?
line 1 especially
line 2 is just to give description its not needed
it wont fuck up my first cmd?
why would it?
idk im a paranoid person
try and see
alright
will update!
worked, just 1 more issue arising dk what its about
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\Josh\Desktop\Ultimate\ULTIMATE.py", line 69, in receipt
datetime_object = datetime.strptime(date, '%m/%d/%Y')
AttributeError: module 'datetime' has no attribute 'strptime'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'receipt' raised an exception: AttributeError: module 'datetime' has no attribute 'strptime'
!d datetime.datetime.strptime
classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") corresponding to *date\_string*, parsed according to *format*.
If *format* does not contain microseconds or timezone information, this is equivalent to:
```py
datetime(*(time.strptime(date_string, format)[0:6]))
``` [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime "time.strptime") or if it returns a value which isn’t a time tuple. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat "datetime.datetime.fromisoformat").
its datetime.datetime
its just that it worked when ti was not a discord bot
maybe you imported from datetime import datetime
and now you did import datetime
yep
why tf are u so smart wth
glad to hear that
hello guys, I am trying to add a cog to my python discord bot.
This is my bot's class
class Bot(commands.Bot):
def __init__(self, command_prefix, intents, self_bot=False):
commands.Bot.__init__(self, command_prefix=command_prefix, intents=intents, self_bot=self_bot)
self.add_cog(General_commands(self))
This is my cog class
class General_commands(commands.Cog): # addded commands.Cog after "Down" suggestion
def __init__(self, bot):
self.bot = bot
@commands.command
async def status(self, ctx):
await ctx.send('Bot is online!')
This line -> self.add_cog(General_commands(self)) in Bot's class throw this warning "RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited" that basically says that I have to await that function call ( which I read too on stackoverflow ). If I add the "await" statement ( so it becomes await self.add_cog(General_commands(self)) ) I get the error "SyntaxError: 'await' outside async function".
It doesn't work in any way. I mind if I placed the add_cog to the wrong place. I tried to place it even outside the __init__ method, so in the main, but I still get the warning "cog was never awaited".
Does anyone suggest any solution? I would appreciate it a lot
First of all the class must be a subclass of commands.Cog
right!
second thing
you need to call @commands.command
third thing
the .add_cog is awaiable
meaning you need to await it
where?
I know but I get this
and you can put await only in async functions
so load it in setup_hook or else
I have to async the init
init cant be async
okay
override the setup_hook method
and load it here
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
now it works without errors, I just get Command "status" is not found
how do you load the cog?
# inside bot's class
async def setup_hook(self) -> None:
await self.add_cog(General_commands(self))
okay and did you change the thing with @commands.command i told you to
👍
uhmm when i add a on_message(), my @client.command() doesnt work anymore
why?
when i remove on_message() the command works fine tho
Try to add await
i did
Btw im using replit
It says the same thing 
What is even module1 and module2?
Because such module doesn't exist
but how i can launch the script please ?
because there is the modules is writed on the script and i have to install it to launch the script

libs.eazyui import Colors, Colorate, Center
libs.solver import Solver
annyone?
Send the link to it's documentation or pypi page. Idk from which library are these. I don't see any mentions of them in google
@buoyant quail can you help me ?

.
looks like those are the ones defined in the script already
From where did you get it?
you can have your own modules
github 
and looks like this modules are those
then send the github link
but it's a friend's script @buoyant quail
then ask friend :/
he doesn't reply
xd
its from a github repo called Discord-Token-Generator, its indeed from a folder called libs
It's always me. How can I add slash commands using discordpy?
can we even help with it
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
it on replit ?
its in the github
if you copied it there, then yes
There are many external libraries, is there an official one?
@buoyant quail creating discord tokens do not respect discord TOS ?
we wont assist you with it its against python discord rules
no idea i just search that 2 import lines on github and it matched that repo, which has a silly readme
ah ok can you just tell me how to unpack zip files on replit ?
i dont use replit
see this example for slash commands in discord.py https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
sugar daddys 💀
thank you
how can I remove the "this interaction failed" from dropdowns (considering everything works fine apart from this weird message) ?
without using interactions
Respond something to interaction or defer it.
:incoming_envelope: :ok_hand: applied timeout to @whole fable until <t:1689778565:f> (10 minutes) (reason: attachments spam - sent 10 attachments).
The <@&831776746206265384> have been alerted for review.
ten attachments 
just told I didn't use interactions. This is my code
class biome_selection(discord.ui.Select):
def __init__(self, userid):
options = [discord.SelectOption(label="Swamp"),
discord.SelectOption(label="Desert"),
discord.SelectOption(label="Woods")]
super().__init__(placeholder="What biome do you chose ?", options=options)
self.userid = userid
async def callback(self, ctx):
if ctx.user.id == self.userid:
await ctx.message.channel.send(content=f"{ctx.user.mention} successfully chose {self.values[0]}")
class Drop(discord.ui.View):
def __init__(self, userid, name: str):
super().__init__()
if name == request.classSelection():
self.add_item(class_selection(userid))
elif name == request.biomeSelection():
self.add_item(biome_selection(userid))
# TODO : add the remaining selections
request is just a class containing a few strings to handle the (many) dropdown menus. The call in my main file looks like this, right now it's just testing :
@bot.command(name = "biome")
async def test(ctx):
view = Drop(ctx.message.author.id, request.biomeSelection())
await ctx.message.channel.send(ctx.message.author.mention + "choose a biome", view=view)```
If you name an interaction ctx it still will be an interaction.
you mean I can just do ctx: discord.Interaction and it'll work ? or ctx is instantely recognized as an interaction
oh alright thanks
how can i make bot using python
with such question i can only refer you to documentation
https://github.com/Rapptz/discord.py
https://discordpy.readthedocs.io/en/stable/index.html#
Hi
what
censored?>
So i'm making a discord bot that is powered by chatgpt and i can't seem to get the bot to send a message
What
can't send py? wt
Sorry but best format i can send...
print("command warn") print(friendly_message) async def get_channel(): channel = bot.get_channel(1077629150262730814) asyncio.run(get_channel()) await channel.send(friendly_message) print("sent message to channel",channel)
tried looking on stackoverflow, but thats the best i could find and doesn't work
And where you call get_channel function? Except inside itself
Oh let me pull up the full code
I guess you don't because you'd got an infinite recursion
what?
async def get_channel(): ?
yes
yes?
You defined the function. It won't run until you will call it.
Oh so all i need is to call it?
Yeah
oooh
And remove asyncio.run(get_channel()) from it
Because it will call itself infinitely
'ill see if it works 👀
Hmm didn't seem to work. I've got
this error
RuntimeWarning: coroutine 'on_message.<locals>.get_channel' was never awaited
get_channel()
elif command == "warn":
print("command warn")
print(friendly_message)
async def get_channel():
channel = bot.get_channel(1077629150262730814)
await channel.send(friendly_message)
get_channel()
print("sent message to channel")
got it
actually you can just get the code out from function
because it's kinda useless here
huh i get invalid syntax
Hmm
werid, so i went before on discord.py documentation and just copied their send message in channel snippet but it seems to need something to be defined
?
ok I'm probably blind but I don't seem to find the way to make a dropdown menu clickable a single time by a user in the doc, what's the magic line to do that
Just delete/disable it in the callback
that would make it clickable a single time
I meant a user could only use the menu once
and any other user could use it, but a single time too
Such thing doesn't exist in discord itself, implement it by yourself
Remember the users who clicked inside and don't answer them next times
I have one more question... How would i go on banning kicking and muting a member. Would like reason too to msg dm the user
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
is a json file enough or do I go big with a db considering I'll use one later ?
i'm not that familar with guild...
can you just do it by user? <@>?
whats guild anyways
Then you have to get familiar with both guild and member if u want to implement the commands above
Yeah is there any documentation i can look at to learn more
Servers are called guilds in discord.py
Ah i see now
Search discord.py docs on Google it will come up
is it bc members can have server names and such
I'll recommend u use a db since json is not a db
yeah i did try but couldn't really find anything usefull related to banning muting kicking... i did but not really what i wanted kinda
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
!d discord.Guild.kick
await kick(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`kick_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") to do this.
Thanks
someone giving away a very simple bot with slash commands? Pls, I'm new to python programming and old tutorials don't work
lol, i'm working on a bot
maybe when i'm done i can give it to you
Hey guys
powered by chatgpt plus it's free and no need for paid plan
Do you think Having a Discord bot as a Command center for some personal and work related stuff would be suitable ?
it moderates
I'm not sure what to use for this kind of usecases, what do you use in these scenarios?
There are many open source projects on github you can download and run by yourself
I'd guess memory is enough
Or you are going to store that for a long?
Then yeah, would be better to use db later
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Do i need to put it under @bot.command for it to work?
because thats not even working
thats what i got:
if command == "ban":
# Perform action for ban
print("Performing ban action")
await ban(user, reason=reason, delete_message_days=1, delete_message_seconds=0)
@buoyant quail
would it need to be member.ban?
ye
ok
i'm getting UnboundLocalError: local variable 'member' referenced before assignment
does it have to do with my indentation
would this work? member = guild.get_member(user["id"])
had this part in my code just wasn't using it to ban
maybe
depends on what user is
user = message.author
Not enough context, can't give an accurate answer
!e
class User:
pass
user = User()
user["id"]
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | user["id"]
004 | ~~~~^^^^^^
005 | TypeError: 'User' object is not subscriptable
Then just use that user :/
I bet you'd get the same kind of error
What?
would i need to provide user id?
member = guild.get_member(user["id"]) <=== id?
or is that to GET the id?
or to input the id no
You already got the member object from the message object
you mean the when a message is sent?
No, it's an attr, not item
And you can already get the user/member object from the message object
!d discord.Message.author
i ask again from this right????? async def on_message(message):?
Ok so i don't get it, member is not going to be defined?
but it's under the message function
If you don't define it, then it wouldn't
And? Why would that matter
what do i define? thats what i'm not getting
I didn't tell you to define anything
It can be any variable of Member instance
Get it from the message
Doesn't matter how you name it
You named it user, then use user
user.ban
Ok
Ok that seems solved, but why does it say it only takes 1 arg? TypeError: ban() takes 1 positional argument but 2 were given
i just put await user.ban(user, reason=reason, delete_message_days=1)
TypeError: ban() takes 1 positional argument but 2 were given
the documentation even gives 3
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
The method takes no positional arguments
Yes that see?
Then what would be correct syntax if i want to ban certain user with reason and 1 day worths of messages?
If Python doesn't raise the SyntaxError then the syntax is correct
sorry my bad didn't mean 'syntax'
!e
def a(*, b):
print(b)
a(0)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | a(0)
004 | TypeError: a() takes 0 positional arguments but 1 was given
i mean the correct argument useage
!keyword
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Sometimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• /tag param-arg (Parameters vs. Arguments)
Ok i get it
but the documentation doesn't make it clear how to actually use it no examples given?
It doesn't have to
What do you mean not specific use cases
They can't just give you all possible examples
like not using seconds, no reason given,etc
You'd already know that if you know Python enough
It shows the parameters definition and explains which parameter what takes and does.
Lol, i just took basic python in one of my school classes
nothing fancy
hi
can you just explain how i use the ban command correctly?
What command
are you talking about the guild.ban method?
yeah i'm using user.ban
and what you have already?
user = message.author
and thats it?
yeah
now you have User or Member object
await user.ban(user, reason=reason, delete_message_days=1)
User have a ban method?
i just noticed what im saying
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
Yes it tells me i have too many args
so you are doing the ban method on a Member object already
so no need to pass user to the method
it already knows who to ban
all you can pass to it is this
(this is not literally equivalent to the Guild.ban)
They take different arguments
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
i would show you how it works in the source code but it prolly wont make it clear for you
sure do that?
all it does is it references the guild and passes the arguments you have plus the member itself
whats missing in delete_message_days: int = MISSING, here?
from the docs: ```py
delete_message_days (int) –
The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7. Defaults to 1 day if neither delete_message_days nor delete_message_seconds are passed.
Deprecated since version 2.1.
It's just a default argument
you should use delete_message_seconds instead
what if i want days
the : int part says that it should be of type int and the = MISSING assigns default value as MISSING constant
ok so just put the value in missing
!e py amt_of_days = 10 print("How many seconds is that?:",amt_of_days * 3600 * 24)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
How many seconds is that?: 36000
you dont
you just dont pass it then its default to it
huh
A day has 3600 seconds!? 😨
you know what default values for arguments are in functions?
ok 
!e
def a(b = 101):
print(b)
a(202)
a()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 202
002 | 101
uhhh i'm not getting it
look above
whats the supposd to be 
The argument will be supplied by the default argument if you don't pass it
!e ```py
shopping_list = {}
def add_item(item_name, quantity=1):
if item_name in shopping_list.keys():
shopping_list[item_name] += quantity
else:
shopping_list[item_name] = quantity
add_item("Bread")
add_item("Milk", 2)
print(shopping_list)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'Bread': 1, 'Milk': 2}
we add item Bread but we did not give quantity so the default value was used (quantity=1) 1 in this case
but when adding Milk we provided the quantity so its used instead
does that make it clear?
what you dont understand
you just do await member.ban() and optionally you can provide reason and delete_message_seconds
yeah but why can i provide them all
? thats fine
what do you mean by that
thats fine i don't mind just giving the reason only, but what if i want to provide delete_message_seconds?
Then provide it?
then you just provide it?
Yes, but it tells me that only 1 arg is allowed??!
!e ```py
def ban(*, reason=None, delete_message_seconds=None):
print(reason, delete_message_seconds)
ban(reason="some reason")
ban(delete_message_seconds=100)
ban(delete_message_seconds=200, reason="some cool reason")
ban(reason="some other cool reason", delete_message_seconds=300)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | some reason None
002 | None 100
003 | some cool reason 200
004 | some other cool reason 300
what tells you that
you get an error?
Yeah that makes it clear
i was doing it wrong
await user.ban(user, reason=reason, delete_message_days=1)
TypeError: ban() takes 1 positional argument but 2 were given
so should i just define it as a function
Member.ban does not accept user argument like i said
cool
I have a question
would you be able to join my server and test the bot? seems that i can't ban my self
Hi
yeah guess i'll do that smh
Can I add two datetime objects?
No, you can only add a datetime to a timedelta, or add two timedeltas together
You can also subtract a datetime from another datetime to get a timedelta
How do I convert a datetime to timedelta?
2023-08-18 11:00:54.854651 I need to add this to the current time
You don't, they are two different things conceptually
datetime is a point in time, such as 01/01/2000 00:00
timedelta is a duration of time, such as 1 hour or 10 years
Think about what you're trying to do, adding two datetimes just wouldn't really make any sense
Hmm yeah so what would I have to do?
Well I wouldn't know unless you gave some more context, it's your code 
I just need to add current time and the old time, which is like I sent
idk if it fits here but just a question - i am doing a bot with a moderation command to change permissions in roles/users. it separates groups of permissions in sort-of linux way (read - read chat log, see channels; write - write messages, speak in channels; etc...). someone knows how i could make a group of such permissions so i can have only 3 sets of such permission groups and then only combine command parameters? right now it looks like this and i dont like it:
elif arg1 == "3":
await member.edit(
permissions=discord.Permissions(embed_links=True,
attach_files=True,
add_reactions=True,
use_external_emojis=True,
send_tts_messages=True,
use_slash_commands=True,
stream=True,
use_voice_activation=True,
priority_speaker=True,
send_messages=True,
speak=True,
change_nickname=True,
create_instant_invite=True))
i'd rather sort of that but idk if its ever possible:
read = ("read_messages"=True, "see_channels"=True)
write=("send_messages"=True, "join_voice"=True)
...
elif arg1 == "3":
await member.edit(
permissions=discord.Permissions(read,write)
Perhaps dictionary unpacking is what you're after
sort of...
!e ```py
def f(**kwargs):
print(kwargs)
perms = {"embed_links": True, "attach_files": True, "add_reactions": True, "use_external_emojis": True}
f(**perms)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'embed_links': True, 'attach_files': True, 'add_reactions': True, 'use_external_emojis': True}
ok, very thx
not sure if you can pass the permissions as string though
!e I have no idea why the fuck you want to add 2023 years to the current date.. but:
from datetime import datetime
print(datetime.strptime("2023-08-18 11:00:54.854651", "%Y-%m-%d %H:%M:%S.%f") - datetime(1, 1, 1) + datetime.now())
i know no but looks now like doable
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
4046-03-05 05:17:50.849624
what about using enums?
Yeah I worded that wrong. I need to get the difference between the two times then add that to an old time
They will be not the strings
It's kwargs
ah yes
You can subtract datetimes. And you can subtract/add timedeltas. Do anything you want with that 

How does adding times work?
what is 1 PM + 2 PM?
3PM?
is that what you want in your code?
I'm not too good at explaining, I think that's what I want yes. I save a json file with an expiry date for a user, so !e user 30d, that saves the time in 30d from now, but if I run the command again !e user 15d, I want it to get the duration from the old expiry date and now, then add that to the new expiry date
if the user runs !e user 30d you should save 30 into your database as the duration
does !e just "bump" the expiry, actually?
But if I do that I won't know when it actually expires
wdym?
@slate swan Hi i ran into an issue. So when the bot kicks a user it says that it kicked x person for x reason but some some reason it looks like this:
kick_reason = (user," was kicked reason: ",reason) thats what i used
this is the member object representation
however in my cmd its correct
property mention```
Returns a string that allows you to mention the member.
and it uses user too
ah okay, set the expiriation date in the database then
each time they run it, get the expiriation from the database, add a timedelta to it
what you want to display in the discord
that
the username?
yeah
:/ 1 sec
can't understand why in my cmd window it's correct
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.name "discord.User.name")
Could you show me an example
cause in discord its using reprezentation while in the terminal its using string converter
discord/member.py lines 367 to 374
def __str__(self) -> str:
return str(self._user)
def __repr__(self) -> str:
return (
f'<Member id={self._user.id} name={self._user.name!r} global_name={self._user.global_name!r}'
f' bot={self._user.bot} nick={self.nick!r} guild={self.guild!r}>'
)```
is there a way i use that output
ok
but are you sure you want that #0
@bot.command()
async def set_expiriation(ctx: commands.Context, days: int) -> None:
current_expiriation: Optional[datetime] = # this comes from the database
new_expiriation = (current_expiriation or datetime.now()) + timedelta(days=days)
# save new_expiriation into the database
you can just use member.name to get only the username
like this kick_reason = ((str(user)," was kicked reason: ",reason)?
why you make it a tuple
Does this work if the database expiry time is a datetime object?
it only works if it's a datetime object
then how?
hence the typehint
just use a string already?
f"Some text {some_varriable} some other text"
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
? user = str(message.author)
no convert it to string only when converting to username
oh thats number to string right?
what str() does that
i know i meant str()!
username is a string?
i feel like im lost
doesn't seem to
?
then your code is incorrect
show your code maybe
hard to visualize it
Any custom class can do that if you will define __str__ or __repr__
Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.
When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.
Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.
class Foo:
def __init__(self, value): # constructor
self.value = value
def __str__(self):
return f"This is a Foo object, with a value of {self.value}!" # string representation
def __repr__(self):
return f"Foo({self.value!r})" # way to recreate this object
bar = Foo(5)
# print also implicitly calls __str__
print(bar) # Output: This is a Foo object, with a value of 5!
# dev-friendly representation
print(repr(bar)) # Output: Foo(5)
Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!
? kick_reason = ({user}, was kicked reason: ",{reason})
well thats long
without the "
still why make it a tuple?
aren't tuples a list of numbers ☠️
no ..
lmao
i think you tried to define fstring
but forgot about the f" ... " part
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
look closely at the example
hmm it's saying you can't add int and datetime.datetime
are you adding two datetime objects?
create a converter to convert the 30d input into the timedelta object
def get_time(duration: str):
now = datetime.now()
time = ''.join(char for char in duration if char.isdigit())
one_day = timedelta(days=int(time))
return one_day + now
I was using this
to convert from 30d?
that removes the d and then covnerts it to the datetime
so it only supports days?
yeah I can't even figure out this lmao
if its only for days just input only number
and dont use converter
I'm gonna expand it once I can figure out adding the times
i can show you example of such converter
this might be helpful: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
A hands-on guide to Discord.py

what should I do?
Anything you want. You are a free human 
^ Robin
expand it to accept all possible units or just annotate as int and accept only days

If I expand it by using your converter is it easier to add the times?
it returns the timedelta already
so you can just add it to datetime
it returned 15 days, 0:00:00, but this isn't an actual time since the database will always have it as 15?
any idea what I should do? @slate swan
does anyone know why my task is running many times
@tasks.loop(minutes=30)
async def update_links(self) -> None:
print('running')
async with aiohttp.ClientSession() as session:
async with session.get(self.FLAGGED_LINKS_REPO_URL) as resp:
self.flagged_links = set(await resp.json())
this prints running multiple times within the first 30 seconds
but when i remove all the aiohttp code
@tasks.loop(minutes=30)
async def update_links(self) -> None:
print('running')
it only runs once
where are you starting this task?
another but quicker question - someone knows if i made this good? wanted a command for sending server invites 🙂
@commands.command()
@commands.has_permissions()
async def useradd(self, ctx):
invte = await ctx.create.invite()
await ctx.send(f"url: {invte}")
Why you have an empty has_permissions?
And ctx.create isn't a thing, unless you added it yourself
cause was copying one command (this command was among moderation commands)
there is no such thing like ctx.create
no, like i'd like to generate discord invite and then send it as message
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
!d discord.ext.commands.Context.channel
Returns the channel associated with this context’s command. Shorthand for Message.channel.
in the cog_load
def cog_load(self) -> None:
print('here')
self.update_links.start()
its only printing here once also
are you using discord.py?
yeah
looks like he does, and bot is cogged
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
didnt work
okay, but then how to send it as message in generic text channel ?
like you would normally?
using ctx.send
may i ask what you are trying to achieve
like that?
@commands.command()
async def useradd(self, ctx):
invte = await create.invite(*,temporary=False, unique=True)
await ctx.send(f"url: {invte}")
no
what is create
try using a Semaphore
TextChannel have such methods
alright
it does not appear out of nowhere
thats why i had ctx earlier
Context is still not TextChannel
current text channel i mean
im trying update a list of discord scam links from a github repo every 30 minutes
no Context is Context
@commands.command()
async def useradd(self, ctx):
invte = await ctx.channel.create.invite(*,temporary=False, unique=True)
await ctx.send(f"url: {invte}")
still a no
bruh
then idk lol
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
look how the method is named
ahh, ok, now i see
yeah but it still wont work
*,temporary=False, unique=True from where did you get this?
@commands.command()
async def useradd(self, ctx):
invte = await ctx.channel.create_invite(*,temporary=False, unique=True)
await ctx.send(f"url: {invte}")
what else to add?
from reply above
you are not supposed to copy it
ok then
it just tells you what you can add
if you want the default values it has
just dont pass it
ok, but with that assign it will ever work?
?
like invte = await ...
docs will tell you everything
Returns
The invite that was created.
Return type
Invite
more i'll test and find out xD
huh even that didnt make a difference. i also tried asyncio.Lock() insetad of the asyncio.Semaphore(1) also
def __init__(self, bot: Bot) -> None:
self.bot = bot
self.flagged_links: set[str] = set()
self.lock = asyncio.Semaphore(1)
async def cog_load(self) -> None:
print('here')
self.update_links.start()
async def cog_unload(self) -> None:
self.update_links.cancel()
@tasks.loop(minutes=30)
async def update_links(self) -> None:
async with self.lock:
print('running')
async with aiohttp.ClientSession() as session:
async with session.get(self.FLAGGED_LINKS_REPO_URL) as resp:
self.flagged_links = set(await resp.json())
how about you create a task that runs every 30 mins
oh you have it
hmm
then whats wrong with it
its triggering the task multiple times on startup
yeah that i dont really understand
how about you add print("something") in the __init__
and see how many times it prints
sure
only once
so the task is registered once as well
how you know there is more running at the same time
what's the typehint for member or role
A hands-on guide to Discord.py
Union right
ah you want this or this
then yes union its explained here https://fallendeity.github.io/discord.py-masterclass/converters/#union
A hands-on guide to Discord.py
async with self.lock:
print('running')
async with aiohttp.ClientSession() as session:
async with session.get(self.FLAGGED_LINKS_REPO_URL) as resp:
self.flagged_links = set(await resp.json())
the print('running') is happening many times within 30 seconds
same issue, i think i might know why tho
well the lock was my idea
if you are using Python 3.9 or lower then yes
I'm on 3.10 but I like that way better
sure then
will work too
coould be something witht await resp.json() because the task is getting stuck here probably because the github file im trying to download is 540 kb
sorry for asking yet more but someone have idea to fix that thing?
File "/home/runner/Tux-bot-cogged-update-as-of-8122/cmds/moderation.py", line 8
muted = (view_channel=False)
^
SyntaxError: invalid syntax
its after this question earlier about refactoring role command (to split permissions from long lists of such )...
it needs to be a dictionary
this is a tuple, not sure what your intention is, but you probably want a dict
ok
perms = {"permission": True, ...}
from the docs: ```py
import asyncpg
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
self.data = []
self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
self.batch_update.start()
def cog_unload(self):
self.batch_update.cancel()
@tasks.loop(minutes=5.0)
async def batch_update(self):
async with self.bot.pool.acquire() as con:
# batch update here...
pass
you can add exceptions
lemme check that out
!d discord.ext.tasks.Loop.add_exception_type
whats wrong with it?
add_exception_type(*exceptions)```
Adds exception types to be handled during the reconnect logic.
By default the exception types handled are those handled by [`discord.Client.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect"), which includes a lot of internet disconnection errors.
This function is useful if you’re interacting with a 3rd party library that raises its own set of exceptions.
i literally had
await member.edit(permissions=discord.Permissions(read_messages=True))
... but that cant:
execute = (read_messages=True)
await member.edit(permissions=discord.Permissions(**execute))
...
use a dictionary like i said above
then you can unpack like this
will see
ah there was a json error, i thought a task would display the exception. thanks a lot
i dont
the funny thing is that i thought the same thing but when i added a raise ValueError() in the task, it showed the error
Hm
odd
oh i just checked
and by default discord.py silences aiohttp.ClientError
self._valid_exception = (
OSError,
discord.GatewayNotFound,
discord.ConnectionClosed,
aiohttp.ClientError,
asyncio.TimeoutError,
)
and if it catches these exceptions it will retry the task
which explains why it was running multiple times
except self._valid_exception:
self._last_iteration_failed = True
if not self.reconnect:
raise
await asyncio.sleep(backoff.delay())
Hi, can I get help not with Discord bots, but with bots on internet?
I want to make 10 bots that will come to one website and do some repetitive task
Like clicking, pressing key...
is there a reason why this doesn't work?
role = discord.utils.get("muted")
user.add_roles(role) No error i just don't get the roll i added named muted
I tried with Macro recorder but it doesn't really work
I ran two browser windows on my VM and it was quite heavy on my RAM but I need 10 not 2
@slate swan
My friend told me about Selenium but I don't know how to work with that
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
read the docs, how is it supposed to know where to look and what to look for
if you have role id you can just guild.fetch_role then you can just pass the id
i saw this on stack overflow maybe its old
docs > stack
source code > docs 
okay, lets go back to that server invite command...
code here:
@commands.command(aliases=["adduser"])
async def useradd(self, ctx):
invte = await ctx.channel.create_invite()
await ctx.send(f"url: {invte}")
doesnt output anything either in chat or console. like if i didnt ran command. any ideas?
What channel would ctx be
current where command'd be invoked
if i'd type $adduser into #bots then invite would lead to #bots ... etc
I always do ctx.channel
Maybe ctx.send is a thing too
Does the command even run? Any errors?
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
why "probably"? run it and find out
send part is fine, invite part is broken so it doesnt continue and i know it, idk just where exactly
i have lots of send things in code and all works
what do you get when you run that command
yep, i restarted server few times and is in cog
in same file commands are working
its 100% thing with invite
Hello,
I've been trying for some time now to create a role allocation via a select menu for my discord bot (cog). My problem is none of the bot host supports DiscordComponents, Select, SelectOption what I need. Who knows a solution or a host that supports this?
btw - i went back with that code :
@commands.command(aliases=["adduser"])
async def useradd(self, ctx):
invte = await ctx.create_invite()
await ctx.send(f"url: {invte.url}")
although code with ctx.channel wasnt working too
discord.py has support for that built in
the command is fine
then what?
¯_(ツ)_/¯
@iron cosmos ^
idk. check my code then...
https://replit.com/@hacknorris/Tux-bot-cogged-update-as-of-8122#cmds/moderation.py
means - didnt checked after refactor too much but something was working
Mhh strange
You did put everything in the __init__
WELL... forgot if i ever had it lol, i wasnt touching that bot for a year
edit:
def __init__(self, bot):
self.bot = bot
was at top, so probably it shouldnt be an issue
or i should move command one tab left..
if I typehint user: Union[discord.Member, discord.Role] how would I check if the mentioned was a user or member?
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
probably last question today. i have that code for automod but it doesnt catch swears if first or last word:
with open("bad-words.txt", 'r') as f:
global badwords
words = f.read()
badwords = words.splitlines()
@bot.listen("on_message")
async def swears(ctx):
msg = ctx.content.lower()
for word in badwords:
if word in msg:
await ctx.delete()
any ideas?
means - i added spaces in this file with world list but i'd like to know how to see words automatically and to separate words by space (exact words, not word-in-middle of another..)
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/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/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
like if in word list i'd have that: apple, pear, grape
and i'd like to filter out apple but NOT pineapple
but also i'd be able to catch first, last words and words without spaces around
(pineapple not filtered but pine.apple already yep)
ctx part is fine, i talk more about regex now
yeah but why not name it something that will be helpful
its not about it, i dont care about code quality but working functions
plus - i dont want to swear right here (i dont want ban xD)
readability speeds up productivity 
!e
import re
s = "apple, pear, grape;IDK !!! fmdskmk34534 hey .. mhmhm"
print(re.findall(r"[a-zA-Z]+", s))
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
['apple', 'pear', 'grape', 'IDK', 'fmdskmk', 'hey', 'mhmhm']
ok, thx
@slate swan How do I get the members from a role again
!d discord.Role.members
property members```
Returns all the members with this role.
what type is returned?
Idk if It’ s just me but I cant rly think of an example where you would need to “filter apple but not pineapple” for profanity filtering. Like I cant think of a swear word that becomes ok if you add something to it.
you're reinventing the wheel here,
discord has a built-in setting for swear words, or blacklisted words, don't try to recreate it, because people will ofc be smarter and find workarounds for your "swear words detection system"
example
you blacklist "apple", people start typing @pple or appl3 or appIe (this is uppercase i)
... 🤷♂️
I feel like for every new feature discord adds public bots become more useless.
that's good news, it makes managing servers for non-devs very user-friendly
you shouldn't depend on third party bots all the time
because if it breaks, you're screwed because you have no control over it
can I call len on role.members to get the total amount of users with a role?
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
How do I get the snowflake ID?
Does discord.utils.get with ctx.guild.roles as the iterable accept role ID?
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
huh
what's the reason of doing it? https://github.com/Rapptz/discord.py/blob/master/discord/utils.py#L484-L486
discord/utils.py lines 484 to 486
# global -> local
_all = all
attrget = attrgetter```
2023-08-30 16:01:49 is there a way to convert this to discord timestamp like <t:1693436509:F>
I know you could convert it to an epoch but isn't there a built in method?
what fields are timestamps useable in?
What would be best to constantly check dates from a file? should I setup a task?
What exactly are you trying to do?
Once the current time has surpassed the time in the file I want to remove the date from the file
What will this achieve? just asking because there may be a better way
it will remove a role from the member
Go to the discord.py server (.gg/dpy), go to a bot channel and type ?tag future task
@tasks.loop()
async def yourtask():
# if you don't care about keeping records of old tasks, remove this WHERE and change the UPDATE to DELETE
next_task = await db_conn.fetchrow('SELECT * FROM tasks WHERE NOT completed ORDER BY end_time LIMIT 1')
# if no remaining tasks, stop the loop
if next_task is None:
yourtask.stop()
# sleep until the task should be done
await discord.utils.sleep_until(next_task['end_time'])
# do your task stuff here with `next_task`
# UPDATE the task to mark it completed, or DELETE it
await db_conn.execute('UPDATE tasks SET completed = true WHERE row_id = $1', next_task['row_id'])
# add a `before_loop` and `wait_until_ready` if you need the bot to be logged in
yourtask.start()
# in a command that adds new task in db
if yourtask.is_running():
yourtask.restart()
else:
yourtask.start()
Yeah thats wha tyou would use
what you trying to do?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Its faster to Access local varriable than global so if its used more than once its better
seems like premature optimization to me, but i guess im not the person that would be handling thousands/millions of elements
I thought about it, but _all is used only one time
Ahh,, in the loop
its used many times
ye

