#discord-bots
1 messages · Page 199 of 1
but groups would work too?
yes
you can typehint a parameter with discord.Attachment
I feel like that's more of a simple method though
@app_commands.command()
async def command(interaction, attachment: discord.Attachment):
...
ye @torn sail used a simple method .
cause you can just have everything chilling at the top
ok
how interaction send file
do interaction:discord.Interaction
don't just pass in interaction in your function
does discord.File exist fr
ya
any error
404 Not Found (error code: 10062): Unknown interaction
ngl, I can't solve that problem. First time seeing that error
ok i have to send_message then followup.send
It might take over 3 seconds to reach that code
So yeah defer and use followup
what defer
i agree with the guy above me
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
who wants to help me make a bloxflip predictor dm me. I need good, pro python dev to help me
would mean the world if yall could help me out
just dm me
Oh nvm
i got this output here:
Roll.find_brackets() takes 1 positional argument but 2 were given
def find_brackets(self, **args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total
hey i have a short question im new and trying to figure out why this is shwoing
What is showing
Assuming that is pycharm, click on the error counter in the top right of the window (it should have green ticks and yellow signs at least)
But usually they can be ignored
thats likely a warning saying intents are required but missing
if i have a giant command (2000 lines)
is it appropriate to break it down into multiple functions and have the actual command pass in ctx to each of them one by one?
uh yes if its 2000 line please split it up
A single command with 2000 lines!? 🙀
hope that command find a way to time travel or something with that many lines
I don't know how to fix my error
Don't name function the same as imported modules or anything really
is that holding back the coding to not work? I don't know what else to name it
yes, it shadowed your discord module, you can just change the function name so it doesnt overshadow it. ```py
@bot.command(name='discord')
async def _discord(ctx):
...
this way, the name of the command is still `discord`
thank you i figured that out i have a new error in #1035199133436354600
how can i transfer something from one class to another
https://paste.pythondiscord.com/mufulipare
Code^
Issue: My UI does not work error above can someone please help
category is probably none
they made a help channel here https://canary.discord.com/channels/267624335836053506/1076357065330671676
i saw
Help me make a discord bot fuckers
Subclassing?
Bro watch your language
Read the code of conduct.
!rule 1
1. Follow the Python Discord Code of Conduct.
I begged like anything 10+ times no reply
can i have help with this please 😄
https://paste.pythondiscord.com/wuxilirove
what's wrong with it
the bot won't run
you have a while true loop and you can't do that with async
the while true loop will never finish and your bot will never run
File "C:\Users\Administrator\Desktop\main.py", line 86
global current_page
^^^^^^^^^^^^^^^^^^^
SyntaxError: name 'current_page' is used prior to global declaration
you didn't define current_page either
do something like current_page = 0, but you shouldn't even really use globals they're bad practice
!globals
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
That is certainly sad
when will you realize that people have their own time and that you aren't entitled to help
sometimes we have lives beyond discord
I feel called out
people will eventually help, but you need to be patient and not rude
can views be in ephemeral messages
Yes
i made a discord bot that can automatically process cryptocurrency purchases
with discord.py
it supports bitcoin, ethereum and litecoin
i have no issues i just wanted to show it off
i just need to make it look better but idk how
the embed is basic
make it use only one edited message and add an embed color + author icon that changes depending on the crypto
orange for bitcoin etc
it would look way cleaner
also add a “cancel button” using a view that can cancel a transaction before the money is sent
you can't cancel a transaction after it's been on the blockchain
“before the money is sent”
while it’s still expecting it
i was gonna use buttons or a modal but thats too much effort
maybe in the future i will
it would take me like a whole hour
it’s just 20 extra lines
which requires research
idk anything about discord.py
all i know is how to make a dropdown
makes sense
i only made it because i had to manually review everyones purchases
now i dont need to worry about that
automatic + faster
@slate swan do you use some crypto exchange service API or something else
yes i do
i would use a crypto library personally
i have one but then i need to make custom addresses myself and its a pain to manage them
Cause ik bitcoin is just purchases linked into a blockchain but where the hell is that blockchain located
the crypto exchange generates address for me and then tells me how many confirmations the transaction has
once it reaches the required confirmations, i get the crypto sent directly to me
if they purchase with btc -> i receive ltc
if they purchase with ltc -> i receive btc
it’s decentralized across all bitcoin nodes
idk if im right or wrong but i think the actual blockchain for making transactions etc is blockchain.com
its an automatic advertising thing
one hour of advertising is $0.10
??? bitcoin is not centralized
it’s not run by one website
idk if im right or wrong
anyone can run their own bitcoin node
why do u even use crypto then just use paypal or something
then whats the point
wdym whats the point
crypto is easy
and i trust it way more than something like paypal
well you thought it was run by blockchain.com
for making transactions
so u trusted blockchain.com but not paypal
yeah it’s just a wallet
in a rude way
tone is hard to interpret over the internet
you can’t know if it was rude or not because everyone sees it differently
its quite clear what u meant
yeah what’s wrong with that message
is english not ur first language or something
please stop
i wasn’t being rude, im genuinely tired and half asleep right now im not trying to start anything
i understand just think abt the way u say things
!ot also
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
minimod 💀
But where are they located and how we can interact with them without exchange services if we can?
anyone can run a bitcoin node
Ah so companies just run the nodes
you should look it up, im not great at explaining it
@echo mural
Ok
no, anyone mining bitcoin is running a node and i can run one rn
!d range
class range(stop)``````py
class range(start, stop[, step])```
The arguments to the range constructor must be integers (either built-in [`int`](https://docs.python.org/3/library/functions.html#int "int") or any object that implements the [`__index__()`](https://docs.python.org/3/reference/datamodel.html#object.__index__ "object.__index__") special method). If the *step* argument is omitted, it defaults to `1`. If the *start* argument is omitted, it defaults to `0`. If *step* is zero, [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") is raised.
For a positive *step*, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and `r[i] < stop`.
For a negative *step*, the contents of the range are still determined by the formula `r[i] = start + step*i`, but the constraints are `i >= 0` and `r[i] > stop`.
sort the list in reverse then send to discord bot
where do they get the information from though
No really need, range does that
unless the list is premade and contains numbers with different steps
what kind of bot is it?
In a less expensive way
Uh yeah didn't think of this
it handles automated crypto purchases
oh nice
But wait, to make a purchase you need to give out your private key don't you
i use an exchange api
Or any sort of credentials that are needed to interact with exchange API
Yes ik but they are 100k members cant 1 member help??
u mean how they find eachother
Or it just waits for purchases
how do they know theres a new block?
300k and no it doesnt work like that
because they send that info to each other
i dont understand
public key
Probably in a similar way torrents do
Ah nvm
Just agree discord=80% toxic
again ur not entitled to help
they generate an address from the exchange with my bot and then it listens for a deposit
Purchases must be signed with private key and verified with public one iirc
speaking like that certainly wont get you anywhere
Sometimes we can't help everyone
they have to be signed but i dont need to handle that since exchange does it for me
Ok I understood
only sender signs transaction
If there's no member that can help you maybe ask chatgpt
Yes that's what I meant?
Although not a reliable source
bruh
I'm not able to hear anything on voice channel while using discord on browser, now can I fix my browser settings

@vale wing i use fixedfloat.com api
its a public crypto exchange that doesnt require any information or accounts
only takes a 0.5% fee too
all i need to do is create an order and give the buyer the address and it will handle it all for me
So like I typed..
import discord
And it said ModuleNotFoundError: no module named 'discord '
did you install it?
Like in my computer? Yeah!
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Alright!
Hi! I have this code ```py
class GeneralCM(commands.Cog):
def init(self, bot: commands.Bot) -> None:
self.bot = bot
#adds all functions in this class to the context menu
for func in [getattr(GeneralCM, func) for func in [func for func in GeneralCM.__dict__ if not func.startswith('__')]]:
self.bot.tree.add_command(app_commands.ContextMenu(name=func.__name__, callback=func))```
I'm getting a TypeError: context menus cannot be defined inside a class error and the cause seems to be that when I am getting the function, it is not bound to the class, how can I fix that? when I add the function manually it works fine, but I want to automate it
Also the list comprehension does return all added functions correctly
It's clearly telling you that context menus can't be defined/created in a class
whats a context menu
Message/user commands
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.context_menu why not use the decorator?
!d inspect.getmembers + why not use decorator fr
inspect.getmembers(object[, predicate])```
Return all the members of an object in a list of `(name, value)` pairs sorted by name. If the optional *predicate* argument—which will be called with the `value` object of each member—is supplied, only members for which the predicate returns a true value are included.
Note
[`getmembers()`](https://docs.python.org/3/library/inspect.html#inspect.getmembers "inspect.getmembers") will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom `__dir__()`.
how do I send a file through a bot? is it file=file?
@vale wing Because TypeError: context menus cannot be defined inside a class we can't, that's why I have to use this other method, but getting a function this way seems to unbind it, which is what i'm trying to fix
Declare them as staticmethods?
Is dpy really that dumb that it doesn't allow methods to be added as context menus
Disnake allows that
What do your functions look like
It is ok, we fixed it, by using getattr(self, func) it refers to the instance and thus gets bound
thanks though!
what's the point of doing this, it will work same as self.func
because func is of string type, so I need to convert it to be usable
oh, makes sense
import discord
import sys
import subprocess
client = discord.Client()
@client.event
async def on_ready():
print(f"Logged in as {client.user}")
@client.event
async def on_message(message):
global msg
msg = message
if message.author == client.user : return
if str(message.channel) == channel and message.content.startswith("#python3"):
try :
run = subprocess.run(
["python3", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")
elif str(message.channel) == "python-interpreter" and message.content.startswith("#python2"):
try :
run = subprocess.run(
["python2", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")
if name == "main":
channel = sys.argv[2] # enter channel name you want to run bot
my_secret = sys.argv[1] # enter discord bot token
client.run(my_secret)
in this code i am getting error
client.init() missing keyword-only arguement : 'intents'
hi
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
How can i find an application subcommand with the subcommand name? Like /find subcommand test
!intents
@white citrusi am still setting same error
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'
please solve this error
File "/home/runner/discord-bot-that-run-Python-Program/discord-bot-that-run-python-programs.py", line 5, in <module>
client = discord.Client()
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'
!index
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
It's pretty obvious why it occurs isn't it
!e
a = [8, 30, 567]
print(a[2])
print(a[3])```
@vale wing :x: Your 3.11 eval job has completed with return code 1.
001 | 567
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | IndexError: list index out of range
I was also confused by the error when I first encountered it 
💀💀
python is 0 indexed you do realise?
!e
a = [8, 30, 567]
print(a[1])
print(a[2])```
@naive galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 30
002 | 567
import os
import os
import discord
import sys
import subprocess
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
client = discord.Client(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print(f"Logged in as {client.user}")
@client.event
async def on_message(message):
global msg
msg = message
if message.author == client.user : return
if str(message.channel) == channel and message.content.startswith("#python3"):
try :
run = subprocess.run(
["python3", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")
elif str(message.channel) == "python-interpreter" and message.content.startswith("#python2"):
try :
run = subprocess.run(
["python2", "-c", message.content], capture_output=True, text=True
)
await message.channel.send(f"<@{message.author.id}> \n Output : \n{run.stdout} \n\n Error : \n {run.stderr}")
except Exception as e:
await message.channel.send(f"Exception Occurs : {e}")
if name == "main":
channel = sys.argv[2]
enter channel name you want to run bot
my_secret = sys.argv[1]
enter discord bot token
client.run(my_secret)
can u solve in this
i m still getting that error
This is not really how you should run the python code with discord bot unless you limit it to yourself-only
Imagine someone executing os.system("sudo rm -r /*") and that's where you say goodbye to your system
Also use commands framework for commands
https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
😭
Bye bye vps or computer
os.remove("main.py") and bye bye your bot
You need to sanitise input
They need to completely isolate environment, there are millions of ways people can bypass the "sanitation" with
Similar to python's snekbox
Ig
can you make a TextInput required if another text input is x?
Discord don't allow you to change it when during the time that the user is using the modal
@client.command(aliases=["wl"])
async def whitelist(ctx,*,opt,user:discord.Member):
if ctx.author.id != ctx.guild.owner.id:
await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description="You Are Not Authorized To Use This Command.",colour=0x2f3136))
return
if db[f"{ctx.guild.id}"] not in db.keys():
if opt in ["add"]:
db[f"{ctx.guild.id} a"] = {
"gname": ctx.guild.name,
"whitelisted" : [user.id],
}
elif opt in ["remove","rem"]:
db[f"{ctx.guild.id} a"] = {
"gname": ctx.guild.name,
"whitelisted" : [],
}
else:
if opt in ["add"]:
if user.id in db[f"{ctx.guild.id} a"]["whitelisted"]:
await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"User {user.mention} Is Already In Whitelist.",colour=0x2f3136))
return
else:
db[f"{ctx.guild.id} a"]["whitelisted"].append(user.id)
await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"Added {user.mention} To Whitelist.",colour=0x2f3136) )
elif opt in ["remove","rem"]:
if user.id not in db[f"{ctx.guild.id} a"]["whitelisted"]:
await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"User {user.mention} Is Already Not In Whitelist.",colour=0x2f3136))
return
else:
db[f"{ctx.guild.id} a"]["whitelisted"].remove(user.id)
await ctx.send(embed=discord.Embed(title="Antinuke Whitelist",description=f"Removed {user.mention} From Whitelist.",colour=0x2f3136))
why is it missing an arguement when i type
wl add 12345678
Command raised an exception: TypeError: whitelist() missing 1 required keyword-only argument: 'user'
@vale wing
How do you get a category?
what category
get a category by id
how
:|
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
use this
that works for categories?
Yes
a category is a channel, yes
oh
Should I type hint it to CategoryChannel right?
help me pls
Ya it'll return a CategoryChannel object
.
You're using a * in your command params. So everything after the command name in the message is being sent as "opt".
what should i do then
Remove the aterisk?
you should be using subcommands instead of taking an argument and checking what it was
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
examples/basic_bot.py lines 63 to 76
@bot.group()
async def cool(ctx):
"""Says if a user is cool.
In reality this just checks if a subcommand is being invoked.
"""
if ctx.invoked_subcommand is None:
await ctx.send(f'No, {ctx.subcommand_passed} is not cool')
@cool.command(name='bot')
async def _bot(ctx):
"""Is the bot cool?"""
await ctx.send('Yes, the bot is cool.')```
here
Hi, I was trying to make an embed as usual for my bot
score_embed = discord.Embed(title="Scoreboards", description= None)
reaction_embed = discord.Embed(title="Grab your team role here!",
description="Teams are randomized for balance.")
and further into the code,
score_embed.add_field(name=role.name, value="0")
But for some reason it spits out this error:
score_embed.add_field(name=role.name, value="0")
AttributeError: 'NoneType' object has no attribute 'name'
I have no idea why an already created embed is defaulting to None. Both pieces of code belong to the same command - start.
When I run the same file on Python itself, it returns this error:
NameError: name 'score_embed' is not defined
Both the definition and the code trying to add a field lie in the same scope
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Here's the entire code for the command start
This is old code written for previous d.py versions and I'm currently updating it, I've also checked the docs for any inconsistencies in version 2.0 but couldn't find any
is it possible to make custom cooldown in slashes?
I don't think anything like current_guild exists, unless that's a custom attribute of your bot
about this?
i am getting this error pls tell me what is wrong with code
ImportError: cannot import name 'constants' from partially initialized module 'bot' (most likely due to a circular import) (/home/runner/bot-1/bot/bot.py)
Anybody got an idea for utility command?
The error already did
@client.event
async def on_ready():
global guild
guild = await client.fetch_guild(guildid)
l.info(f"Watching {guild.name} {guild.member_count}")```
i am getting member count as None
@naive briar
oh thnks vro i got it
!d discord.Intents.members you need this
Whether guild member related events are enabled.
This corresponds to the following events...
client=commands.Bot(command_prefix=".",intents=discord.Intents.all())
What is the problem?
from selenium import webdriver
driver= webdriver.Chrome()
url="https://www.hepsiburada.com/dyson"
driver.get(url)
my_element=driver.find_element("id","addToCart")
my_element.click()
ı runned this codes
!e
def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total
print(find_brackets(2d6+[5*1d4]/1d3))
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 26
002 | print(find_brackets(2d6+[5*1d4]/1d3))
003 | ^
004 | SyntaxError: invalid decimal literal
!e
def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total
print(find_brackets("2d6+[5*1d4]/1d3"))
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 26, in <module>
003 | TypeError: find_brackets() takes 0 positional arguments but 1 was given
!e
def find_brackets(**args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total
print(find_brackets([2d6],[[5],[1d4],[1d3]]))
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 26
002 | print(find_brackets([2d6],[[5],[1d4],[1d3]]))
003 | ^
004 | SyntaxError: invalid decimal literal
anyone up to help, from my discord bot i receive this error:
Roll.find_brackets() takes 1 positional argument but 2 were given
it don't even enter the function
def find_brackets(self, **args):
total = list()
if args.values() not in [start, end, mod, is_outside]:
start = list()
end = list()
for num, i in enumerate (args):
if "[" in i:
start.append(num)
if "]" in i:
end.append(num)
print(start, end)
mod = 1
is_outside = True
total = self.find_brackets(start, end, mod, is_outside)
else:
for i in range (mod, start):
if start[i] > end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append(start[i], end[i])
del end[i], start[i]
if(is_outside == False):
break
return total
pivot = self.find_brackets(args_result)
it's suppose to use **kwargs
args is just the name for kwargs
then you're calling it in the wrong way
here
**kwargs means that the function can take any keyword argument
your function is accepting self that is automatically passed by python and an indefinite numbers of kwargs, however you're passing a positional argument when calling the function, python is passing an argument too and here's the reason why you got the error
i see, it's confuse cus i learned that self thing was a default thing
guess when i use kwargs i need to change something
but what?
pattern = re.compile(r"[+-*\/]")
args_result = pattern.split(args)
args = 2d6+[5*1d4]/1d3
or anything that input into this:
@commands.command(aliases = ['r', 'diceroll', 'dice_roll', 'dice'])
async def roll(self, ctx, args):
so it's a list, isn't it?
yup
ok, I would make find_brackets accepting *args, you'll call it as self.find_brackets(*args_result)
args will be in your code a tuple, so you need to remove any inexistent method
you can't accept it as kwargs
like this?
you could take it directly as list too
yeah, FYI this will unpack the list
this makes more sense
will i need to change this too?
essentially you're just swapping from list to tuple and it's useless imho
yeah
like this?
yeah but read the message that I wrote above
guess i will need to remove .values() thing
remving the .values() thing i get this
well, i don't know how i will remove the inexistent methods
guess i'm missing some point
i never messed with *args and **kwargs, so it's a new thing for me
the program can't find the element, that mean that this element (element("id","addToCart")) isn't on the screen
you mean if start in args or end in args or mod in args or is_outside in args?
yes
bit it all meant to not being in that
guess i will need to check up the number of arguments
how do i make it check the lenght of my *args?
like, i'm planning to when it's just 1 arg it makes the first thing
else it just pass to the other thing
ops, i mean how many args is in the input
tat's what i'm trying to check
len(args)
guess that's not what i'm searching for
cus it printed 4 instead of just one
guess i need to gather the number of lists
like, if it just have 1
or i guess if there is 1 thing
or 4
i'm planning to [2, 4, 6, 8] being counted as 1
while 2, 4, 6, 8 being counted as 4
that doesn't make sense
func(*[2, 4, 6, 8]) this is 4
func(*[[2, 4, 6, 8]]) this is 1
whats the discord testers server link?
do you mean this one? https://discord.gg/discord-developers
could someone possibly help in https://discord.com/channels/267624335836053506/1076625922507145357 🫶
Helloo, I'm having problems with the token and wanted to ask if someone could help.. I get the error:
Client.run() missing 1 required positional argument: 'token'
But it isn't missing in my code.
My code in that line is:
client.run(discord_token)
And I have defined "client" and "discord_token" in another file and imported it correctly
I also get the same error when I put the token in directly.
discord testers has been closed afaik
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
how do i make it so only the author of the command can use the select menu?
interaction.user
Read the docs
It'll help
Or you can use ephemeral=True
https://paste.pythondiscord.com/vimevojusi
error
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 87, in training
view = DropdownView(interaction.user)
TypeError: DropdownView.__init__() missing 1 required positional argument: 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'training' raised an exception: TypeError: DropdownView.__init__() missing 1 required positional argument: 'author'```
You want everyone can see the select menu
That just makes the message only visible to the interaction author
Or only the author?
I know
everyone
That's why I suggest that.
but i want onyl the uathor to use it
^
You have 2 same views, why?
Pass the new argument(interaction.user) in the init of the view and then define it as self.author or self.whatever
line 10, in <module>
client.run('DiscordToken')
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
someone help please
i don't understand why i got this erorr
class DropdownView(discord.ui.View):
def __init__(self, author, bot, timeout=30):
self.bot = bot
super().__init__(timeout=timeout)
self.add_item(Dropdown(self.bot))
self.author = author
async def interaction_check(self, interaction: discord.Interaction):
return interaction.user.id == self.author.id```
@bright wedge
What the f
line 10, in <module>
client.run('DiscordToken')
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
someone help
Are you even inputting the token
yes i just didn't want to show it here
Do you have the proper intents enabled
..?
i dont know, do i??
where i check that
Seems ok, try it.
Bot application info
Scroll down a bit you'll see intents
Make sure you enable the ones you're using
Some Gateway Intents require approval if your bot is verified. If your bot is not verified, you can toggle those intents below to access them.
PRESENCE INTENT
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 81, in training
TypeError: DropdownView.__init__() missing 1 required positional argument: 'bot'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/kaiso-staff-assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'training' raised an exception: TypeError: DropdownView.__init__() missing 1 required positional argument: 'bot'```
is it that
@dim cosmos
Yeah
It's obvious error.
there is no enable button
🤦♂️
replit moment
there is no bot argument
if there is you need to pass it
view (bot=define the bot,author= define the author).
you only passed 2 or 3 arguments
what?
And idk why you are passing the bot as argument.
help me instead
Bro it's a simple button how can't you find it
Oh my god
xD
It's not rocket science
ok
same error
Where do u have ur intents defined
im confused
In the code
Exception has occurred: ClientConnectorSSLError
Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)
The above exception was the direct cause of the following exception:
File "C:\Users\My.Name\import discord.py", line 10, in <module>
client.run("DiscordToken")
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:997)]
lemme show the whole code
Just show me the intents part
import discord
intents = discord.Intents().all()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game(name="Watching my self get worked on"), status=discord.Status.online)
client.run("discordToken")
the whole script
i think so
Did you save changes
yes
view = DropdownView(bot, interaction.user)
Idk reset ur token & restart
alr 2 sec
Bro sry but I can't help if you don't know basic python,sry again!.
same error
-_-
just because im confused because i haven't done this before, doesn't mean that i don't understand basic python
I'm having problems with the discord token, I get this error:
Client.run() missing 1 required positional argument: 'token'
But it isn't missing in my code.
My code in that file is:
if __name__ == '__main__':
client.run(discord_token)```
And I have defined "client" and "discord_token" in another file
I also get the same error when I put the token in directly.
Why are you doing discord.Intents().all()
Its a basic Objects as Arguments and Parameters.
It's discord.Intents.all()
oh
That should do it
same error
oh i forgot to mention
i get an anti virus notification every time i do run it
if that maybe messes it up or something
🤦♂️
don't be rude, it's not necessary after all.
@dim cosmos
asked chatgpt,
answer:
This error message suggests that there is a problem with the SSL/TLS handshake when the code is trying to connect to the Discord server using the aiohttp library. Specifically, the SSL/TLS handshake failed because of a SSLV3_ALERT_HANDSHAKE_FAILURE error.
This error could be caused by a number of things, including an incorrect SSL configuration, outdated SSL libraries, or network connectivity issues. Here are a few things you could try to resolve the issue:
Check your network connectivity: Make sure that your internet connection is stable and there are no firewall or network configuration issues that could be blocking the connection.
Update your SSL libraries: Make sure that your SSL libraries are up to date and there are no known vulnerabilities that could be causing the issue.
Check your SSL configuration: Ensure that your SSL configuration is correct and matches the server requirements. If possible, try to connect to the server using a different SSL version or cipher suite.
Try using a different library: If the problem persists, you could try using a different library to connect to the Discord server, such as the Requests library.
If none of these steps work, it might be worth contacting the Discord support team to see if they can provide any additional assistance.
view DropdownView(bot=bot, author= author, interaction.user)
what does it say
Yes
lemme try again and see
Pass the right arguments in your object.
File "main.py", line 80
view = DropdownView(bot=bot, author= author, interaction.user)
^
SyntaxError: positional argument follows keyword argument
@dim cosmos
Another obvious error
Pause protection for a bit & try again
author=author,<----
ok
view = DropdownView(bot=bot,author=author,interaction.user)
author=interaction.user
ohhh
...
I'm traumatized
don't be rude, it's not necessary after all.
ok
That's not being rude but ok
is it possible to make it so the selectmenu disables after someone chooses an option
Make sure, will work with bot=bot or will be bot=self.bot
Yeah
how do i do that
You disable it on interaction
didnt work
Paste the error
can you help me with that
There is many ways to do that
I mean you want to remove the select menu from the message or just make it not working?
Let's see
actually, ill remove the select
Goodnight
Then you can edit the message
view=None right
And define the view as None view=None
That will remove the view (the select menu in your case).
to have access to the view message you can use interaction.message
And do whatever you want (edit,delete,copy etc).
Hi there, how do I fix this error?
main.py:18: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension("cogs." + f[:-3])
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = '/', intents=discord.Intents.all())
def load_cogs():
"""
Pulls every .py file in the /cogs folder, and treats it like a cog.
only cogs should be in the /cogs folder.
"""
for f in os.listdir("./cogs"):
if f.endswith(".py"):
bot.load_extension("cogs." + f[:-3])
def load_key_and_run():
"""
Loads the first argument passed after 'python3 main.py',
and treats it as a bot token.
this allows you to run the bot by using:
python3 main.py tokenGoesHere
"""
bot.run("token")
if __name__ == "__main__":
load_cogs()
load_key_and_run()
thanks
Load your extension in async function
load_extension it's a coroutine so do await load_extensions.
Read this.
oh
so like this? ```py
async def load_cogs():
for f in os.listdir("./cogs"):
if f.endswith(".py"):
await bot.load_extension("cogs." + f[:-3])
ok
Seems ok
uuh SyntaxError: 'await' outside async function
import asyncio
asyncio.run(load_cogs())
ok
Why is it only doing this locally and not on my VM?
dont do asyncio.run with load_cogs, because you wont be able to run your actual bot that way.
instead in your load_key_and_run function, make that async, instead of bot.run use bot.start (since bot.run is sync and it'll block), and in your load_key_and_run function, do await load_cogs()
THEN, do asyncio.run(load_key_and_run())
Vps?
i mean deadass it's just a server I keep in my room under my desk
Well we use setup_hook function
ok lemme try that
okay? cool? they arent using setup_hook, im simply giving them an actual working solution to how they want their code lol
yeah ofc
Well idk without tests
do you use bot.sync anywhere?
no
from discord.ext import commands
import discord
class PingCog(commands.Cog, name='Ping'):
def __init__(self, bot):
self.bot = bot
@commands.slash_command(description='Check the latency of the bot.')
async def ping_command(self, ctx):
embed = discord.Embed(
title="Pong :ping_pong:",
description=f"Latency: `{round(self.bot.latency * 1000)}ms`",
color=0x0000ff
)
await ctx.respond(embed=embed)
def setup(bot):
bot.add_cog(PingCog(bot))```
this is code for my ping...
oh you're not using actual discord.py you're using some fork
lol
?
i don't know then sorry, best you can do is ask in the server for the fork you're using so they can give better help since they obv know the fork better than most here
idek i used someone's bot to start off and build another bot on top of it
how would I use that?
bot.sync is for acutal discord.py itself not the fork you're using so its basically useless here sorry, best you can do is this ^
How am I using a fork tho
Your cog file is wrong
i can tell because commands.slash_command that doesn't exist in actual discord.py
Btw
wut
Your cog file is from old version
The official docs for the new discord.py version,
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
ok
How can i find an application subcommand with the subcommand name? Like /find subcommand test
Is there somewhere like a basic pre-written discord.py bot with a ping and test slash command so that I can base myself off of that?
the example that was just posted above...?
it has example slash commands, with a bunch of comments too explaining what each does and how 
oh ok sowwy
lol
whats wrong with my code??
||hi leo||
code?
and try to use the unicode instead of the emoji directly whenever possible
!charinfo 💰
it's the same thing
it is the same thing but the encoding of the emoji might differ with the platform and might cause encoding error while doing operations like printing and stuff, while using the Unicode directly makes it completely safe
i want to dynamically add some buttons to a view, but i have some decorator buttons that i want to stay at the bottom
how would i do this?
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
yeah ik
maybe add the other buttons dynamically too
so i have a buncha add_items in __init__
actually
oh that's an idea
iirc you just give your buttons the highest row number of 4 and it'll stay on the bottom
oh 4 is the highest row number? lol
0 to 4
so i have a view that can hold multiple values
like at the end of a game you've win, lose, or draw
should this be a string or enum
i want to make a number go up +1 everytime the command is used
for example
i used ?warn (user)
the case number would be 1
and i used it again and it'd keep going up
how would i do that
you'd need a database for that
@ui.button(label="Toggle Map", row=1, style=discord.ButtonStyle.blurple)
async def toggle_map(self, i: discord.Interaction, button: ui.Button):
if i.message.attachments:
i.message.attachments = []
await i.response.send_message("Map hidden", ephemeral=True)
else:
i.message.attachments = [self.loc_img]
await i.response.send_message("Map shown", ephemeral=True)
```how do i make this do what i want it to do?
Are you trying to send an attachment? https://discordpy.readthedocs.io/en/stable/api.html?highlight=file#file look into Files. Also, doing i.message.attachments = [self.loc_img] won't do anything. If you want to change the original message to show or hide the image do something like await interaction.message.edit(file=<the file object>
ok now it gives this lmao
Your file is empty
idk how to show you that it definitely isn't
Can you send the code where you make the File
file = None
if show_map:
file = discord.File(
mark_location("hometown_map", *u.HTOWN[pos]["coordinate"]),
filename="hometown_map.png"
)
view = Decision(a, file, choices)
await adventure_msg.edit(embed=embed, attachments=[file], view=view)
await view.wait()
mark_location returns an io.BytesIO object
Did you close the byteIO object?
i don't believe so
well, turns out i had to add this line:
self.loc_img.fp.seek(0)
```for some godforsaken reason
Hmmm, it should be open for it work afaik
Yeah correct
You were probably reading from the file or writing into it and went to the end of the BytesIO() when you put it into the File()
set up a database
how do i have a button send a modal
already got one
then use it
await interaction.response.send_modal(...)
nice
how do i do it
what db do you have
do you know why?
there's not one database
?
there are multiple databases that exist
and we can't read your mind and figure out which one you use
idk what to do to fix it
you have a typo, it's label
same problem
greetings pythonistas,
I am aware that you register slash commands on your bot using the discord.app_commands module but for some reason, the slash command does not appear for me. tried resetting the client and the bot
what's the best way to add an alias to a command that's inside a group? example: .reminders as an alias to .reminder list
||
||
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
oh?
and now
Have an external third function with your command's logic and call it from both, that's the simplest way
you're using s but it's not defined, what are you trying to do?
a friend tell me
Yep. Every time you add or remove a command, edit a name or description of a parameter, change an annotation or change anything that shows up to the user in the discord UI you need to sync.
I recommend you have a prefix command to manually sync since changing anything in the callback (inside async def) doesnt require to sync, and the sync endpoint is quite rate limitey, so syncing on startup is highly discouraged imo.
works finally ty ^-^
Yay!
try:
with open('commands/factories and etc/enterprises.txt') as f:
company = json.load(f)
await interaction.response.send_message(f"{company[number]}", ephemeral=True)
except Exception as e:
print(e)
enterprises.txt
{
"1": "завода",
"2": "чтото"
}
the console displays "1" and the command does not work, how to fix it?
can I not invoke the .reminders command in the .reminder list command with the logic inside the .reminders command? Or vice-versa?
can u help me?
How
can u help?
define the target
what you mean
Oh hi sarth, we meet again :D
What are the attributes for channel Param?
btw if a channel gets created why would on_channel_update send 3-4 embeds of giving update about Channel?
in which event?
On_guild_channel_create and delete
TextChannel
VoiceChannel
CategoryChannel
StageChannel
ForumChannel
channel can be either of these types
look into attributes of them
text
k
So in guild channel update event how do I provide the information that was updated? Without actually using channel.name etc
no way other than comparing the difference between properties of after and before in dpy
try:
fcommand = nextcord.utils.get(interaction.client.get_all_application_commands(), name=module)
print("1 try")
print(fcommand)
except:
try:
cmd = self.bot.get_application_command_from_signature(module.split()[0], nextcord.ApplicationCommandType.chat_input, guild_id=interaction.guild.id)
fcommand = cmd.children.get(module.splt()[1])
print(cmd)
print(fcommand)
print("2 try")
except:
fcommand = None```
He doesnt find the subcommand with the name
Hi all
I want to make a utility module for discord.py
Do anyone have idea on what should I make
how do i send a file as a link in discord embed?
file as a link?
you want to send a link to a file?
So I have to use the attributes ?
yes
discord.py patcher 🧠 a library that monkey patches discord.py like a doctor and breaks it in every possible way 💀
mhm k
Someone help?
a library that makes discord.py case insensitive
its a discord.file() function
What you mean? You mean i can do
Bot = commands.bot or Bot = command.BOT
but when am sending it in a embed
its showing discord.file(object)
and not the link to download it
you have to use discord.File for sending documents/whatever/images
yep
yea sure
yes
both should work
tf
file = discord.File(filename="files/data.json")
embed = discord.Embed()
embed.description = f"Here is your file: [Click File to dwnload]({file})"
await ctx.send(embed=embed)```
bot = cOMmaNDS.bOT too
filename means the name that the file will be sent with in discord
you have to use the fp argument instead and specify the path to your file
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Would that cause any confusion in code?
thx got it
file = discord.File("files/data.json", filename="NameInDiscordClient")
🛐
i was joking
if you wanna make something related to dpy you can probably make a lavalink extension or helper functions
Traceback (most recent call last):
File "/home/discordbot/modmail/bot.py", line 24, in <module>
from emoji import UNICODE_EMOJI
ImportError: cannot import name 'UNICODE_EMOJI' from 'emoji' (/home/discordbot/.local/lib/python3.9/site-packages/emoji/__init__.py)```
How do I make this look good then?
How to fix this?
you can use the name attr of them instead of the object itself
how? 💀
won’t that give channel’s name?
yep
you'll have to manually check each attribute
something like this
what is lavalink?
music player for discord
In discord.py we can add role with one line of code?
yea
Is it possible to make a bad words filter module for discord.py?
so, if I had to put the content only till 1024 in an embed what should I use?
you can slice off the string
!e ```py
long_string = "a" * 100000
_1200chars = long_string[:1200]
print(len(_1200chars))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1200
@slate swan sarth 
you can use a logic inside the parent command py if ctx.invoked_subcommand is not None: return ctx.invoked_subcommand will be None if there was no subcommand used
I don't think I fully understand
@bot.group()
async def main(ctx):
if ctx.invoked_subcommand:
# a subcommand was used
else:
# subcommand was not used
oh
wait, you're asking asking for something else
you can just create a new command ig and invoke the command you want
@bot.command()
async def reminders(ctx, *args):
command = bot.get_command("reminder list")
await command(ctx, *args)
Can someone help now please?
!return
Return Statement
A value created inside a function can't be used outside of it unless you return it.
Consider the following function:
def square(n):
return n * n
If we wanted to store 5 squared in a variable called x, we would do:
x = square(5). x would now equal 25.
Common Mistakes
>>> def square(n):
... n * n # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
... print(n * n) # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None
Things to note
• print() and return do not accomplish the same thing. print() will show the value, and then it will be gone.
• A function will return None if it ends without a return statement.
• When you want to print a value from a function, it's best to return the value and print the function call instead, like print(square(5)).
!class
Classes
Classes are used to create objects that have specific behavior.
Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.
Here is an example class:
class Foo:
def __init__(self, somedata):
self.my_attrib = somedata
def show(self):
print(self.my_attrib)
To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.
bar = Foo('data')
bar.show()
We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.
!find element
can someone help me with my bot i get the error cannot reshape array of size 32 into shape 5, 5
@bot.command(name="minesv3")
async def minesV4(ctx, server_hash: str):
# Preprocessing of server hash to obtain the game grid
game_grid = []
for i in range(0, len(server_hash), 2):
game_grid.append(int(server_hash[i:i+2], 16))
game_grid = np.array(game_grid).reshape(5, 5)
# Use the trained model to predict the unknown spots
prediction = self.model.predict(game_grid.reshape(1, -1))
prediction = np.reshape(prediction).reshape(5, 5)
# Convert predictions to symbols
symbols = []
for row in prediction:
symbols_row = []
for spot in row:
if spot == 1:
symbols_row.append(":white_check_mark:")
else:
symbols_row.append(":x:")
symbols.append(symbols_row)
# Create an accuracy score for the prediction
accuracy = np.sum(prediction == game_grid) / 25 * 100
# Create the embed for the prediction
embed = discord.Embed(title="Bloxflip Predictor", color=0x00ff00)
embed.add_field(name="Prediction", value="\n".join(" ".join(row) for row in symbols), inline=False)
embed.add_field(name="Accuracy", value=f"{accuracy:.2f}%", inline=False)
await ctx.send(embed=embed)```
Of course it can't
!list
how to fix
!e
print("Hello world")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello world
holy shit
🤯
Ignoring exception in view <DeveloperView timeout=None children=4> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Удалить персонажа' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\githab\BOT\cogs\developer\developer.py", line 65, in SQL_button
SQL = cursor.execute("""DELETE FROM discord.users WHERE (user_id = '567107484850847744');""")
File "C:\Python310\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Python310\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Python310\lib\site-packages\pymysql\connections.py", line 547, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "C:\Python310\lib\site-packages\pymysql\connections.py", line 793, in _execute_command
raise err.InterfaceError(0, "")
pymysql.err.InterfaceError: (0, '')
Dear, good evening. Please tell me what the problem may be. The team works every other time. Sometimes it deletes without question, sometimes it gives an error. why is that?
@discord.ui.button(label="Удалить персонажа", custom_id="Developer-4", style=discord.ButtonStyle.primary)
async def SQL_button(self, button, interaction):
if interaction.user.id != 567107484850847744:
await interaction.response.send_message('Размечтался', ephemeral=True)
else:
with connection.cursor() as cursor:
SQL = cursor.execute("""DELETE FROM `discord`.`users` WHERE (`user_id` = '567107484850847744');""")
SQL = cursor.fetchone()
connection.commit()
print("Удалено")
hey so I'm trying to make some sort of GPT bot and this is what happens when it takes too long to respond
How could I fix this?
I'm using the openai API
@bot.slash_command(name="imagine", description="Give you a response with the prompt")
async def imagine(interaction: discord.Interaction, prompt: str):
openai.api_key = ""
response = openai.Image.create(
prompt="a white siamese cat",
n=1,
size="1024x1024"
)
image_url = response['data'][0]['url']
embed = discord.Embed(
title="Here you go!",
description=f"{image_url}",
timestamp=datetime.datetime.now(),
)
embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
try:
await interaction.send(embed=embed)
except:
openai.APIError
```
where can i hire someone to help me code a discord bot?
I could code a bot
you aren't deferring the response
it takes a long time to send a request to openai and get a result back
Okay
also, that's not how try/except works, it's:
try:
# code that runs
except openai.APIError:
# code that runs if there was an api error
there's also else/finally
No, what lib is that
I'm trying to make a geoguessr bot using the geoguessr api but the bot isn't receiving a challengeid
This is what I've done
so wait, how do I defer then?
await interaction.defer(embed=embed, thinking=True)
I don't how to defer stuff
I'm currently reading the docs of discord.py
how do i perform input validation in a modal?
You have to check after the user submitted
how do I defer?
its not a function?
do I need to import something
what do i do to raise an error and say "hey you messed up"
Wdym
that was meant for me i think
for you i think yeah interaction.defer is the correct function
!e like this?
def func():
raise Exception("owo")
func()
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "<string>", line 2, in func
004 | Exception: owo
No
your saying this is correct?
shouldn't discord have something special for that?
defer don't take embed arg
just do this:
await interaction.defer()
```and u good
so what does it take?
If the command callback raises/causes an error, it will call the error handler
including for modal submissions
it still does not work @ionic garden
await interaction.defer(AI_Message, thinking = True)```
bro just call it w/ no arguments
either way it does not work
well you just called it with arguments, so...
the thing on the docs is just a function signature, it's part of interaction.response so you need to do it on a response object
So I don't understand, do I put py interaction.defer()
before any code?
Can someon ehelp me i keep getting “cannot reshape array of size 32 into shape 5, 5
@bot.command(name="minesv3")
async def minesV4(ctx, server_hash: str):
# Preprocessing of server hash to obtain the game grid
game_grid = []
for i in range(0, len(server_hash), 2):
game_grid.append(int(server_hash[i:i+2], 16))
game_grid = np.array(game_grid).reshape(5, 5)
# Use the trained model to predict the unknown spots
prediction = self.model.predict(game_grid.reshape(1, -1))
prediction = np.reshape(prediction).reshape(5, 5)
# Convert predictions to symbols
symbols = []
for row in prediction:
symbols_row = []
for spot in row:
if spot == 1:
symbols_row.append(":white_check_mark:")
else:
symbols_row.append(":x:")
symbols.append(symbols_row)
# Create an accuracy score for the prediction
accuracy = np.sum(prediction == game_grid) / 25 * 100
# Create the embed for the prediction
embed = discord.Embed(title="Bloxflip Predictor", color=0x00ff00)
embed.add_field(name="Prediction", value="\n".join(" ".join(row) for row in symbols), inline=False)
embed.add_field(name="Accuracy", value=f"{accuracy:.2f}%", inline=False)
await ctx.send(embed=embed)```
that doesn't exist, do interaction.response.defer
Why are you trying to reshape it to that anyway
JUST HOW TO FIX IT
And this doesn't seem like discord bots things
it is
You simply can't
bruh so what do i do
Because NumPy can't
I don't know what to tell you at this point
bruh
it won't work
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=0,
max_tokens=4000,
top_p=1,
frequency_penalty=1,
presence_penalty=1,
stop=["Human:", "AI:"]
)
AI_Message = response['choices'][0]['text']
embed = discord.Embed(
title="Here you go!",
description=f"{AI_Message}",
timestamp=datetime.datetime.now(),
)
embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
try:
await interaction.response.defer(AI_Message, Thinking=False)
except:
openai.APIError```
I just said call it before doing any heavy operation
And with no arguments
Then respond to the interaction later
what do you mean by "call it before doing any heavy operation"
Call it at the top of the function
defer first, then do all your code
Before anything else
also why are you still calling it w/ arguments
wait i'm talking about modals here
rn when i raise an error in on_submit it just says "something went wrong"
it's been five min is this a bad thing?
my bot is doing this?
for the past 3 min
Send it
seems like a problem w/ your ai more than a problem w/ discord
Did you handle the error and respond to the interaction
You still haven't responded to it
was kinda expecting a kinda shaky red box + the actual error message @ the top
class PageView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.current_page = 1
def create_embed(self):
if self.current_page == 1:
description = "This is page 1"
elif self.current_page == 2:
description = "This is page 2"
else:
description = "This page does not exist"
embed = nextcord.Embed(title=f"Page {self.current_page}", description=description)
return embed
@nextcord.ui.button(label="◀️", style=nextcord.ButtonStyle.grey, disabled=True)
async def prev_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
if self.current_page > 1:
self.current_page -= 1
await interaction.message.edit(embed=self.create_embed(), view=self)
if self.current_page == 1:
button.style = nextcord.ButtonStyle.grey
button.disabled = True
else:
button.style = nextcord.ButtonStyle.blurple
button.disabled = False
@nextcord.ui.button(label="▶️", style=nextcord.ButtonStyle.blurple, disabled=False)
async def next_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
if self.current_page < 2:
self.current_page += 1
await interaction.message.edit(embed=self.create_embed(), view=self)
if self.current_page <= 1:
button.style = nextcord.ButtonStyle.grey
button.disabled = True
else:
button.style = nextcord.ButtonStyle.blurple
button.disabled = False
@bot.slash_command(name="hello2", description="Test command")
async def hello2(interaction: nextcord.Interaction):
view = PageView()
await interaction.response.send_message(embed=view.create_embed(), view=view)```
The forward button works but the backwards disabled
interesting way to create a paginator
no
oh
is backwards always disabled?
afaik the fundamentals of views are basically still the same
yes
imo you should combine the button checks into one method and then call it in both buttons
yeah i did that in my paginator
oh
you can just reference the method directly, d.py replaces it with the actual button instance at runtime
e.g. ```py
self.next.disabled = index == 0
@slate swan oh i didnt clarify this, the issue in your code is that you're only updating the button that got clicked, i.e. clicking next doesnt update the prev button and vice versa, hence why im suggesting you update both buttons at the same time, using just one method (the tip above about referencing the button method would be helpful for this)
async def start(self, ctx: commands.Context, *args, **kwargs) -> None:
kwargs["embed"] = self.embeds[self.index]
kwargs["view"] = self.paginated_view
await ctx.send(*args, **kwargs)
self.paginated_view.set_index(self.index)
async def start_with_interaction(self, interaction: discord.Interaction, *args, **kwargs) -> None:
kwargs["embed"] = self.embeds[self.index]
kwargs["view"] = self.paginated_view
await interaction.response.send_message(*args, **kwargs)
self.paginated_view.set_index(self.index)
any better way to do this
i should just let the user handle the sending of the message probably
thank you!
didnt notice, thankss
personally i use one method that accepts either a messageable or an interaction
https://github.com/thegamecracks/thegamebot/blob/v2/bot/utils/paging.py#L246-L253
bot/utils/paging.py lines 246 to 253
async def start(self, channel: discord.abc.Messageable | discord.Interaction, ephemeral=True):
await self.show_page(self.current_source.current_index)
if isinstance(channel, discord.Interaction):
kwargs = self._get_message_kwargs(initial_response=True)
await channel.response.send_message(ephemeral=ephemeral, **kwargs)
self.message = await channel.original_response()
else:
self.message = await channel.send(**self._get_message_kwargs())```
oh i see
is discord.abc.Messageable | discord.Interaction equivalent to Union[Messageable, Interaction]?
what is the difference
the pipe operator was introduced in 3.10 as an equivalent to Union
(or rather, 3.10 added support for using the pipe operator to declare union types)
i see
it would also be nice to let users edit an existing message with a paginated view
maybe i'll create a method like get_starting_embed and get_view
where would I start with creating a dicsord bot?
also I'm not super active on this server so if anyone has an answer please ping me
discord.py has some nice documentation
make sure to follow the slash commands or hybrid command examples, some of the examples on the documentation are outdated
Yup that's what I was confused about, thanks!
im trying to create a soldier game and to attack people i want them to be able to send multiple types and amounts of soldiers for example 100 riflemen 10 snipers 5 bombers. whats the best way to get that in one command?
with slash commands or message commands?
slash
how can i make it that a dc bot responds in a dm to the command
i guess make a bunch of arguments, for message commands i would use FlagConverter
e.g. !attack --riflemen=100
https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=optiontype#discord.AppCommandOptionType
these are the only option types you can have
# slash commands
@bot.tree.command()
async def dm(interaction):
await interaction.user.send("hello")
await interaction.response.send_message("Done!", ephemeral = True)
# message commands
@bot.command()
async def dm(ctx):
await ctx.author.send("hello")
is this the same as app_commands.choices?
choice is a type of argument, which i'm pretty sure is actually a string option type with an autocomplete function
so does it just let you specify what type of parameter a user puts into a slash?
yeah
those are all of the parameter types supported by the discord api
i would just have a bunch of optional arguments for each possible soldier type
that default to 0
amount:
like Riflemen: 0
amount: discord.AppCommandOptionType.integer
?
you can just do riflemen: int = 0 i think
whats appcommadoptiontype for
that's just what discord.py uses to represent the option type
sorry i'm not very good at explaining
i haven't tested the second one
Hey, I've just moved my bot out of a testing server into the real server but one of it's features isn't working. It was working completely fine before so idk y it isn't now, when I was testing the bot I used a separate bot but then combined it with another bot when it was done so maybe it could be something with that. The issue is that on_member_update isn't working.
Nothing prints when I give myself the 'Client' role
@client.event
async def on_member_update(before, after):
print("1")
if discord.utils.get(after.roles, name='Client') and not discord.utils.get(before.roles, name='Client'):
print("2")
category = discord.utils.get(after.guild.categories, name='Reviews')
print("3")
channel = await category.create_text_channel(f"review-{after.name}")
print("4")
await channel.set_permissions(after, view_channel=True, send_messages=False)
print("5")
do you have the members intent enabled? @slate swan
How do I make my slash commands sync into my discord server?
and what does this means?
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
await coro(*args, **kwargs)
File "C:\Python310\lib\site-packages\nextcord\client.py", line 2482, in on_connect
await self.sync_application_commands(
File "C:\Python310\lib\site-packages\nextcord\client.py", line 2296, in sync_application_commands
await self._connection.sync_application_commands(
File "C:\Python310\lib\site-packages\nextcord\state.py", line 829, in sync_application_commands
await self.register_new_application_commands(data=data, guild_id=guild_id)
File "C:\Python310\lib\site-packages\nextcord\state.py", line 1036, in register_new_application_commands
await self.register_application_command(app_cmd, guild_id)
File "C:\Python310\lib\site-packages\nextcord\state.py", line 1071, in register_application_command
raise e
File "C:\Python310\lib\site-packages\nextcord\state.py", line 1067, in register_application_command
raw_response = await self.http.upsert_global_command(self.application_id, payload)
File "C:\Python310\lib\site-packages\nextcord\http.py", line 393, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name: Command name is invalid```
Hey @graceful ermine!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
bot = commands.Bot(command_prefix='*', case_insensitive=True, intents=intents)
@bot.slash_command(name="Ban", description="Bans a user")
async def ban(interacton: nextcord.Interaction, member: nextcord.Member, Reason):
member.ban(Reason=Reason)
interacton.send(f"I have banned {member.mention} for {Reason}")
@bot.slash_command(name="Avatar", description="Shows a avatar of a user")
async def Avatar(interacton: nextcord.Interaction, member: nextcord.Member):
Embed = nextcord.Embed(title=f"{member.mention} pfp!")
Embed.set_thumbnail(url=member.avatar)
interacton.send(Embed=Embed)
@bot.slash_command(name="Joke", description="I will tell you a joke!")
async def Joke(interaction: nextcord.Interaction):
some_joke = [
"What happens when you slap Dwayne johnson in the butt, You hit rock bottom.",
"What did the left butt cheek say to the right butt cheeks, If we stick together we can stop all this shit!",
"What happened to the poo that was shaped like an anchor? It got stuck on the bottom.",
"What do you call a zombie’s butt? A dead end.",
"What do you call a Frenchman shoving a baguette up your butt? A pain in the ass.",
"What do you call a pirate woman with an amazing butt? She was thicc with 7 C’s.",
"What do you call someone who wedged a philosophy book between their butt cheeks? Now, they have a wisecrack in any situation.",
"What does a 9-volt battery have in common with a girl’s butth*le? You know you shouldn’t, but sooner or later you’re gonna give it a lick.",
"What do you say when you submit a patent for a gold-plated butt plug, but some engineers at BMW beat you to it? Guess they are already making overpriced toys for assholes."
]
interaction.followup.send(random.choice(some_joke))
i'm planning to count the occurance of "[" and "]" in this but seems to not working:
for num, i in enumerate (args[0]):
if "[" in i:
pj = i.find("[")
print(pj)
pj = [i for _ in range(0, pj)]
start.append(pj)
if "]" in i:
pj = i.find("[")
pj = [i for _ in range(0, pj)]
end.append(pj)
when i print pj it brings 0 instead of 2 in it
i'm using this input:
[2d6, [[5, 1d4], 1d3, 4d8], 2d5]
def find_brackets(self, *args):
total = list()
if len(args) == 1:
start = list()
end = list()
for num, i in enumerate (args[0]):
if "[" in i:
pj = i.find("[")
print(pj)
pj = [i for _ in range(0, pj)]
start.append(pj)
if "]" in i:
pj = i.find("[")
pj = [i for _ in range(0, pj)]
end.append(pj)
mod = 0
is_outside = True
print(start, end, mod, is_outside)
total = self.find_brackets(start, end, mod, is_outside)
else:
start, end, mod, is_outside = args
for i in range (mod, len(start)):
if start[i] >= end[i]:
total.append(self.find_brackets(start, end, i, False))
elif start[i] < end[i]:
total.append([start[i], end[i]])
del end[i], start[i]
if(is_outside == False):
break
total = total[0]
return total
this is args
that's the output i'm receiving:
0
[[]] [[]] 0 True
How do I sync my slash commands?
line 26, in load
await bot.load_extension(f"cogs.{filename[:-3]}")
^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'load_extension'
i dont really know why.
i am using 2.1.0
code:```py
from discord import Intents
from discord.app_commands import commands
from dotenv import load_dotenv
intents = Intents.default()
bot = discord.Client(
intents=intents,
debug_guilds=[1069881952460603462] # hier server id einfügen
)
@bot.event
async def on_ready():
print(f"{bot.user} ist online")
async def load():
for filename in os.listdir("cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
async def main():
await load()
await bot.start("my token ")
asyncio.run(main())
extensions are part of the commands extension, so you'll need to use discord.ext.commands.Bot
so i needto import that
I'd recommend reading the guide: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
about this
which information do i need to provide more?

