#discord-bots
1 messages · Page 680 of 1
actually a live support
yeah my bot has that
I’m trying to make my discord command display my json data
await ctx.send(json_data)
@slate swan hi thanks my issue is it sends all the json data including the syntax
await ctx.send(json_data["keyYouWant"])
Making a userphone command where one can interact from server to server
**-- Planning -- **
You need:
---> two instances of discord.TextChannel to send and receive the output. These can be gotten by bot.get_channel. We can name these channels x being the server the command was invoked in, and y being the support channel.
---> an on_message to listen for messages sent in channel x and y
---> a db for the on_message to check for. For this i'm going to use json
--> a command to append data to the database
-- Writing --
The on_message may look something like this: ```py
async def support_on_message(message):
data = fetch_data_from_db() #data should be the 2 channel ids. lets pretend its a tuple like (id_1, id_2)
if message.channel.id not in data:
return #we dont care, it hasnt come from one of our support channels
if message.channel.id == data[0]: #id_1
channel = bot.get_channel(data[1]) #get the alternate channel the message
elif message.channel.id != data[0]: #must be id_2
channel = bot.get_channel(data[0])
await channel.send(message.content)
#this pretty much wraps up the one on one support channel stuff. However, it gets more complicated with multiple channelsThe `command` just appends data to the db:py
async def support_channel(ctx):
db = fetch_db()
db.append_data()
eh that took too long to write, i made a couple mistakes while writing it
cogs/Feedback.py line 30
@commands.command(aliases=['dial', 'call', 'assistance'])```
I wrote this using json and a while ago, its not the best but its a nice little starter
thank you i will take a look
Thank you for your effort, but how can I do without a database with only 2 channel id's? I know it's a simple thing but I can't think of it right now
are the id's set?
(will the ids ever change)
no, it will be fixed
Hey so I would like to start making discord bots in py but im having an issue with finding all the resource materials on how to start (like all the functions and stuff like that) could someone please show me where i can find these?
Hey @gloomy ferry! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
prob just make an on_message, check if the id is in either of the channels, and if it is just send the message to the channel with the other id
Hi i keep getting the same error code with cogs, idk what ive done wrong https://paste.pythondiscord.com/emezofagox.py
My bot.pypy bot = commands.Bot(command_prefix=".", intent=intents) for filename in os.listdir('./cogs'): if filename.endswith('.py'): bot.load_extension(f'cogs.{filename[:-3]}') bot.run("token blabla")
error codeTraceback (most recent call last): File "s:\Python\DiscordBot\Regal\cogs\georgebot.py", line 29, in <module> class GeorgeBot(commands.Cog): File "s:\Python\DiscordBot\Regal\cogs\georgebot.py", line 41, in GeorgeBot self.bot.remove_command('help') NameError: name 'self' is not defined
@commands.command()
@commands.has_permissions(administrator=True)
async def activity(ctx, *, activity):
await self.bot.change_presence(activity=discord.Game(name=activity))
await ctx.send(f"Bot's activity changed to {activity}")
needs to be async def activity(self, ctx, *, activity)
you need to have self infront of all
remove self.bot.remove_command('help')
do bot = commands.Bot(help_command=None)
when defining bot
File "C:\Users\George\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\George\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from ediscord.ext.commands.errors.ExtensionFailed: Extension 'cogs.georgebot' raised an error: NameError: name 'self' is not defined```
@manic wing
...
put self as an argument in all the functions
and dont do shit outside the functions
Well this is a great tutorial -> https://vcokltfre.dev/ but you will need oop and asynchronous programming knowledge best of luck
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
i dont understand sorry
thank you!
Also this
@commands.has_permissions(administrator = True)
# Put this into the category it should be cuz idk the category
async def on_member_join(member):
embed=discord.Embed(title="Welcome", description=(f'Welcome {member} to the Regal Community!'), color=self.color)
channel = self.bot.get_channel(869302384004837377)
await channel.send(embed=embed)
hm
Thats not going to work
why?
Theres no event decorator and there is a permission requirement on an event
no event decorator in cogs
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
ohh yeah
how would i store the contents of a variable in a sqlite db
Seems more like a question for #databases
did not realise there was one ty
you are a life saver
WAIT
NOOOOOOOO
i give up, thank you mate. i need some sleep
Alright
Traceback (most recent call last):
File "c:\Users\Stepan\Documents\GitHub\lucifer-helltaker\main.py", line 48, in <module>
async def whitelist(ctx:discord.Context) -> bool:
AttributeError: module 'discord' has no attribute 'Context'
ignore that
remove the :discord.Context
some reason ive linked context to discord
Is it not commands.Context?
yeah but i wired my brain the wrong way
cough bad
why
ok, thats your choice
pycord might be objectively bad compared to the others but I don't have a lot of knowledge about forks
sorry for instigating a disagreement
Your welcome!
I made a Requirements.txt file in my bot should i import that file in the main.py file?
requirements.txt is the naming convention
why would you import it? its purely if you want to install modules
pip install -r requirements.txt
Ok so it is ok now
All of them are pretty trash. Disnake I heard is there only bearable one. Seems to be what everyone else uses here as well.
I myself wouldn’t really know. Personally I will continue to use Danny's repo until a breaking change occurs. And full swap to Novus.
I don't know much about disnake but it changed the import which isn't a good change
!pypi novus
lol you just want this syntax
crap
it copied the wrong thing
i dont blame you
subclassing them is cancerous
can i do?
if tuple in message.content:
yeah seems weird to me
It's the other way around
!d any
If message.content in tuple
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
nah he wants it like that
he prob has a list of filtered words or smthing
yes🚶
So why wouldn't what I sent work as well?
if any(k for k in tuple if k in message.content)
he wants to check if words are in a string…not if a string is in a word
But your not checking words...
Your iterating for each character in the example you sent lol
🤔
so why so?
im checking for each index in the tuple if its in the message.content
for k in tuple
That just sounds dumb
no…
any(word in tuple_ for word in message.content.split())
This would actually, get the words of the message's content
Not each character..
!e ```py
string = "ABCDEFG"
for k in string:
print(k)
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | A
002 | B
003 | C
004 | D
005 | E
006 | F
007 | G
pls reread my logic, im on mobile and i cba to get out-typed when im making better points
Your logic still doesn't make sense after rereading 4 times
It wouldn't work like expected anyhow,
gimme 2 min to get on my pc
!e ```py
string = "grass"
if "ass" in string:
print("yes")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
yes
E.g ^^^
this would trigger the same in your method
No it wouldnt
I split the content into tokens
Oh wait nevermind, were using in
Just replace with equality operator
this is valid, however what you said about message.content in tuple wouldnt work... you have a tuple of 'fuck', 'shit' and the sentance is 'hello fuck'...think it over
@pliant gulch https://github.com/an-dyy/Lefi/blob/master/examples/example_bot.py#L18
It would probably make more sense if you use the parameter provided to get the bots id
Also, I'd recommend not hardcoding any ids in examples (https://github.com/an-dyy/Lefi/blob/master/examples/example_bot.py#L49)
examples/example_bot.py line 18
print(f"[LOGGED IN]: {bot.user.id}")```
`examples/example_bot.py` line 49
```py
@commands.check(lambda ctx: ctx.author.id == 270700034985558017)```
yeah you used in which makes it the same
also it being == would mean fucky or fuck. wouldnt get removed
its all pretty shambolic before regex
split() would split "hello fuck" into ["hello", "fuck"]
That's why you would add fuzzy searching/Can add fuzzy searching
yeah but .split returns a list...and a) you cant put list in tuple and b) you didnt say that
You iterate through each element...
🤦
you didnt say that
you realise we're going in circles because of miscomunication
!e ```py
string = "hello fuck"
tuple_ = ("fuck",)
if [word in tuple_ for word in string.split()]:
print("yes")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
yes
yes but did you say that...
@pliant gulch thx it works but why so?
!e ```py
string = "hello class gentleman"
tuple_ = ("ass",)
if [word in tuple_ for word == string.split()]:
print("yes")
@manic wing :white_check_mark: Your eval job has completed with return code 0.
yes
Yes I quite clearly did in my example
That is right, I guess it's just an old discord.py habbit
I plan on deprecating that parameter anyhow
pls explain🥲
Just like how checking if an element is in a list, if a key is in a dict, etc
so i was doing:
if list in msg:
the first thing you said was message.content in tuple. after 4 minutes goes by, then you decide to show the example
Try saying it outloud
If a list, E.g [1, 2] is inside of a string
That doesn't make much sense now does it
correct
yes
What do you think about the examples btw?
thank you lol
Because that was the issue they were facing
They did it the other way around
At the time, I had ZERO context it was a filtering system
any(word in tuple_ for word in message.content.split())
this is extremely fucking different from
if message.content in tuple

This was their first messsage
Context, context, context
The english language heavily relies on it
i didnt know either
i just assumed - i also said the if any thing 2 minutes before you, but the only thing i didnt add was a .split and apparently 'that sounds dumb'
Because logically speaking, what you did was checking if any of the characters were inside of a tuple
I’m back anyone free to help with my json/discord bot
no, i itered through the tuple not the message.content…
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
i hate you, i had an long text and you deleted it
i think they're fine, but i haven't used the library before. small nitpick though, i don't think the example_ prefixes in the files in the examples directory is necessary
@pliant gulch
Ok, rereading again I see I have mixed the two up
@manic wing hey, i thought you can help me with my bot.
I have an issue that my bot's loading can take up to 5 minutes. After 5 minutes i get on_ready event.
https://paste.pythondiscord.com/xelawodifu.py - dont mind my shitty code
This still would fire off when not expected to anyhow
Ah, I read a styleguide somewhere that this was convention, I guess not; not a huge deal though
it might be, i'm not sure. but yeah it definitely is not a big deal
i agree, adding the .split and changing to equality is recommended, i chose not to over complicate it. anyway
er ill help tommorow, im about to go to sleep
ill chuck in a pull request for the hell of it
me too, just dm me
im an idiot, i thought that was a github link…can i blame mobile coding? dont think so
it is a thing its just discord doesnt have an attr with it because its:
intents = Intents.all()
oh alright
Yep
thanks
Anytime!
you are correct
from discord import Intents
alright
yep
cause what?
What library do you have installed, discord.py?
discord and dpy
?
discord and discord.py
I would suggest reinstalling discord.py
ok i fixed it
the discord package is just a mirror of discord.py, so you don't need to install that
hello I would like to create a server... based off on python development and mainly advertising... so it is compulsory to have a custom discord bot set up rather than already built-in bots... ??
hello?
hmmmm ok... but some built in function doesn't seem to work... though...
hwat is it
the verify system...
you can just invite some other verify bots
like wick
you probably haven't set up the permissions for them yet
umm no.. it is the problem with my code.. My friends also have the same problem... we searched up youtube and wrote this code... but it isn't working...
What about it?
it is showing some kind of error... and my friends also have the same issue...
Glad to solve it if i can
I asked my tutor too, but he can't help with that...
You could send it here theirs allot of knowledgeable people
hmmm yeah... I will share the code...
Can you elaborate on what the issue is? What exactly is the problem what error are you getting? Can you provide full traceback? Can you provide full code? What is it supposed to do? These are all important questions for others to help determine what the bug is and troubleshoot it and help you fix it
Does anyone know how to fix this error?
invite is None
Idk about invites but invite is none lol
currently saves the invitations in the bot's cache, is there any way to make it more effective?
Wish i could help but ive never done it before
help ....
Full tb
tb?
Traceback
Alr
when did u change pfp btw
Like 10 hours ago maybe
how do i use wait_for multiple times?
ok, that error done.. NOW THIS ERROR
oh lol, kk
Your token is none
||imma regenerate token after this|| what the hell is this then ;-;
brah
Change your token
Right now
Your supposed to get a var from an env file
🙂 ...?
Your using vsc?
pycharm
Oh my bad
no, pycharm
anyone?
Well no need for it since pycharm afaik is not public
Pycharm projects are not public. Just put the token in the bot.run() like a normal person
oh ok
bot.run("token1234567890")
(so i can remove os.getenv?)
Yes
k, thanks
Your welcome
My plesure
@small igloo like this^
yee, but can i remove this?
from dotenv import load_dotenv
load_dotenv()]
Yes ofc
yayy ok thanks again xd
Always
I need help making a warn command. can someone help?
cuz am only getting json not py
Don't use json for warn command
sup robin
It's best stored in a database, something like this:
WARN_ID USER_ID MOD_ID REASON
1234 1234 1234 Breaking the rules
If you're using relational of course

i wont
Sql is easy to learn
Very
Can i use ur warn command @sick birch
Sure though it's done using SQL
Been learning it from -> https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
Really good
you can find my github linked on my profile. i wouldn't really use my bot's repo as like a resource though but it might be a decent starting place
My strategy is after i learn to a certain part i stop until the next day and start from zero until i get more pages done then the day before
you can take a peek at how i have mine structured and go from there
where...?
His github is linked to his discord account
linked on my discord profile
lol
i can't stress enough not to use it as a resource though
only as a starting place or to get some sort of idea on how to structure things
ow ok
dont be so harsh on yourself
i mean i did spend a long time working on the bot, talked to a lot of experienced people and tried to implement the best practices but i still can't say it's the best
Everybody has their weaknesses
relatebale
goes double for me lmao
Mine is probably dbs but im learning more about them
Slowly but deeply so i will have no weakness
goals 👍
Yep
Wheres ur warn cmd on your github profile?
After i learn sql and i can use postgres easily i will be learning js and then something else idk i have allot of goals
The hardest part about using postgres for me was actually setting up the database lmao
@sick birch
I installed it for the first time i had zero knowledge and i uninstalled it because it was so complicated but now i will learn sql and take it slowly
let me check
k
For me it's not that its complicated
I just can't be bothered to setup a new database, etc
Oh lol
But if I ever wanted to I can just use my old schema.sql I usually use
And that would automatically setup the database once the manual labour is over
Because its a database server
can be both
Ah i see
Why a server?
Sometimes you can't just have a single file that has all of your database stuff on it
It's not the best for scaling
Ah alr
You can have multiple database servers that manage a single general "database"
kind of like discord bot sharding
Mhmmm
Discord uses apache cassandra and they do this due to the massive amount of data they have to store
Ah i see
How can we code bots like ban, mute or kick
Wdym like the coro?
the library has built in functions for banning and kicking
I thought discord was using Scylla db
They haven't migrated?
Like if mods type a certain command and ping someone it will ban, kick, mute the guy that mod ping
This article was published in 2017
What specifically are you looking for?
Cassandra is very flexible and can scale very well, I don't think they'd switch in a span of a few years
Or not haha
How to code ban, kick and mute
What does it mean by "fully compatiblee with Apache cassandra"?
Ban a member:
await member.ban()
Kick a member:
await member.kick()
Muting requires some extra logic
And youll need a permissions decorator
Means discord won't need to do changes for the same code to work, at least that's what I think
Oh ok
Probably like a plug it and it works type thing
Ye also how do we do tht
"Explore using Scylla, a Cassandra compatible database written in C++. During normal operations our Cassandra nodes are actually not using too much CPU, however at non peak hours when we run repairs (an anti-entropy process) they become fairly CPU bound and the duration increases with the amount of data written since the last repair. Scylla advertises significantly lower repair times." listed as a long term goal, so I think you're right
@commands.has_permissions(administator=True)
async def warn(ctx, member : discord.Member, *, reason=None):
await member.warn(reason=reason)
await ctx.send(f'Warned {member.mention}')``` Can this work?
Warning is a not a native discord feature
You'll have to implement the logic and storing of it yourself
Theirs no such thing as a warn attr with member
You're going to need a database for this. A warn command without a database doesn't serve much functionality
Like this
`if message.content.startswith(j! ban):
await member.ban(What do we put here)
Wouldn't be surprised if later on discord adds a "warn" feature, they've been adding a lot more stuff that bots usually do for a server nowadays
Would be nice, yeah
No you'll have to use a arg and type hint it to a member object
This is pre-rewrite, use the command extension
Would be nice, but I would also very much enjoy for them to add an endpoint if they do add such a feature
Easier interface, easier overall
Can you do the full thing for me I am not good at coding
Yep, discord for the time being has very little native moderation tools
ok
We don't provide code to people, we help them learn
You should get acquainted with Python first before attempting the library. It's not a beginner's library, and it has some advanced concepts such as ayncio.
Sorry i will not do such a thing as i encourage people to work hard and learn by themselves
^
ok
Best of luck to you
What you may be looking for is commissions, where you pay people to write a bot for you. However this is not within the scope of the server and you'll have to do that somewhere else
But I dont understand to much the await member.ban() But what do we put in the brackets
And is against rules of this server
Refer to the documentation
And learn a good bit of python first
It seems you're completely new to the language and I'd strongly recommend against jumping in head first with discord.py as a beginner
You will type hint an arg which is member as a discord member so it will be a member object and with that arg you will use the ban attr which the member obj has
Mostly learn about oop and asynchronous programming
Exactly
Documentation-reading skills are also very important
You'd be surprised how many people come here asking questions which can be solved within seconds with a quick documentation search haha
I was like you but i go against it since i had allot of hard times which i dont recommend
Many,its scary at some points
You're only going to lose interest in it, and having a bad time as a first time programmer will make you stay away from programming in general
First impressions matter
People who learnt haskell as their first lang
Sad how many people have quit due to that reason
APL*
It really is
And it's not something you can easily fix either
I never quit since i love what i do and i put all my passion to what i do
It can keep a person from enjoying programming for life
The sad truth
Your welcome to send it
k
If its ofc related to the channels topic
k
or #❓|how-to-get-help exists
oh
There are plenty of other channels on the left, find one that suits it
Try APL then, I bet you will quit after a few days 👀
okay bc this is most active but ty @slate swan I will take a look there
Depends on the problems relation and what channel suites it best
k
Whats that?
Is that the acronym or...?
Never heard of it
Google it
mm cause this channel includes discussions etc too , whereas those channels are meant for help specifically
Indeed very confused
k
lol
I wonder if you can write discord bots in assembly 
Syntax looks like its from an alien specie
If you want to write enough lines to make your own operating system sure, you could
I mean making a discord bot is really just interacting with their servers and manipulating data
So i suppose you can send instructions to the NIC and whatnot
You can say that
Don't even need to manipulate data
Just communicate with the API and do nothing else
🧠
Yup
Then you'd just have to instruct the NIC card
Pure instructions
I'd assume you'd also be able to connect to the gateway via the network adaptor card as well
right
i'll have to try it sometime...
and put myself through hell
Can we see the actual error?
I have zero idea how to even start a os lol
You can edit the linux kernel on your own if you know what you're doing
Oh yikes replit
Can we see the code?
I think I know what the issue is
Lot of people run into this from my experience
Ah there's the issue
you can't msg from inside
when it's defined on the outside
Python scoping is finicky like that
Also use the rewrite version
The better way to write commands
You're using a really old method
Makes sense
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
avoid following youtube tutorials or stackoverflow posts especially for discord.py
they get outdated really fast and teach you some bad habits
The bot framework is better for commands
The documentation and examples on github
Also asking questions here where people are more than happy to help
https://tutorial.vcokltfre.dev/ <- a fine written tutorial
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
I've seen this one suggested a lot, it's worth giving a read
I see
Probably going to need a database for that
Yep
Premium, I smell mee6
That keeps track of how many messages each person has
You can smell it across the room
Man, message counters are kinda limbo to me tbh
Most bots have premium now
Thing about message counters is they don’t scale very well
Your gonna have gaps in your data
Definitely
Due to some downtimes, etc
You should stay away from replit
About to add a premium version of my bot
It’s globally agreed on that its garbage haha
Don’t be tempted by the dark side
Not really it’s quite a computationally expensive process
I hear my wallet saying "do it"
Unless you update the database on message event
Tbh, depends on how active the user is
The wallet lies
Its too strong
Programming in a nut shell
The endpoint which gets the message history of a user or a channel has a max limit of 100 messages at a time, iir
Each of those is one request
I would go for a different approach, rather then message count levelling is much more tangible to me
Even then it’s quite difficult unless you have some sort of intermediate caching like Redis
on_message
If message is from user, add 1 to that users message count
You’ll need some sort of data storage method that isn’t json
The amount of people that try to use json as a db from online tutorials drives me up the wall
you don't
unless you port forward
sure with something like sqlite
please do
repl.it is globally agreed on to be trash
nah i mean locally
port forward like an sql server or something like that
unsafe though
So you'd make an ngrok tunnel on the same port as your database server
Pass that https IP to repl.it
Im probably gonna leave or maybe comeback because i have a headache but see you guys have a great day
Later, hope you get well soon
Thank you Good night 
Sqlite is a database
And youll need to learn the language SQL as sqlite uses the language to manipulate data
Just to be clear, where exactly are you hosting its repl.it right?
Because if it is, sqlite won't work
Most things are free unless hosting
Do some googling, you should be able to fine one. Just make sure they don't use an ephemeral file system like repl.it
Because file changes will be reset after
And sqlite writes to a file
Ok bye
best of luck
It's not your fault, 99% of tutorials on this subject are terrible
Many people make the same mistake, it's not just you don't worry
vscode is awesome
Sublime is another one
PyCharm also works
Why i cant client.run and bot.run in same file
because you shouldn't have client and bot at the same time
So, how i can put client and bot for my discord bot?
:((
preferable bot since it's more advanced
I cant right?
bot is a subclass of client, so it does everything client can with more
why would you want both
Bro, i want to do some event with client
Does discord bot become slower as more server are added ?
bot can do that
How?
Pls help
That's why sharding exists
What's the limit
about 2000 then you make a new shard
Like how many servers till it's about time
don't take my word for it
Kk mine is 10 server😂
Put the mention ID in () right?
I meant
mention of member
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
@sick birch do u know about overloading?
When one channels position moves why does it make all of them move? In the sense in the channel_update position if one of the channels is moved it logs all of them as a channel moved
I do
Because other channels adjust themselves according to the moved channel?
yeah when you move a channel up the other channels move down to make space
Oh
This is getting more complex than I thought
how can i add text at the end of this?
avEmbed.add_field(name={user.name}
like {user.name}'s avatar
f-strings
So my problem is... I have a paginator, which accepts Interaction as a param. But when I supply it Context, it doesn't work cz I am doing inter.target but ctx doesn't have a target attr... Sooo is there a way, that with overload, I can supply different type of code for a different overload or something?
!e
favNumber = 7
print(f"My favourite number is {favNumber}")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
My favourite number is 7
like so
I don't think you get what overloading is
You're probably looking for a custom context
So here is my code ( I know if statements are v nested)
@commands.Cog.listener()
async def on_guild_channel_update(self,before,after):
disabled = await self.coll.find_one({"Enabled": "False"})
check = await self.coll.find_one({"Moved": before.id})
if check:
await self.coll.delete_one(check)
print("Deleted because yes")
return
else:
if disabled:
print ("Disabled")
return
else:
if before.position == after.position:
print("Position didnt change")
return
else:
print(before.position)
print(after.position)
await self.coll.insert_one({"Moved": after.id})
await after.edit(position = before.position, reason = "Channel moved when lock was enabled")
I am trying to create a channel lock so that when a channel accidentally is moved the bot fixes it itself. However since 1 channel moves all in a 200 channel server the db inserts and deletes are using too much memory.. it works but its very slow and inefficient
Well I don't wanna modify the behavior when an Interaction is passed to the init. I just want it to behave differently for when Context is passed... I'll have to use isinstance?
@sick birch
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: add_field() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
i.. what
!e
class numberWrapper:
def __init__(self, num):
self.num = num
def __gt__(self, other):
return self.num > other
def __lt__(self, other):
return self.num < other
num1 = numberWrapper(5)
num2 = numberWrapper(10)
print(num1 > num2)
@sick birch :white_check_mark: Your eval job has completed with return code 0.
False
So it's there for type checking only and no other use?
async def avatar(ctx, user : discord.Member = None):
if user == None:
user = ctx.author
userAvatar = user.avatar_url
avEmbed = discord.Embed(colour=000000)
avEmbed.add_field(f"name={user.name}'s avatar'", value=f'[download]({user.avatar_url})')
avEmbed.set_image(url = userAvatar)
await ctx.send(embed = avEmbed)```
why doesnt this work?
No it lets you change what operators like < or > or + do
What's the error?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: add_field() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
Wait not that overloading
!d typing.overload
@typing.overload```
The `@overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of `@overload`-decorated definitions must be followed by exactly one non-`@overload`-decorated definition (for the same function/method). The `@overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-`@overload`-decorated definition, while the latter is used at runtime but should be ignored by a type checker. At runtime, calling a `@overload`-decorated function directly will raise [`NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError "NotImplementedError"). An example of overload that gives a more precise type than can be expressed using a union or a type variable:
Lol this one
Oh lmao no haven't used that yet
🤣
you need the name= in add_field
But you'd be better off using a custom context
Hmm
Never knew I'll have to make a custom context for this simple thing 😶
There's a really nice example on the github page
I know how to make a custom context haha
Oh great, should be a piece of cake then
Can someone help me in #help-donut ?
resolved
if someone could help
Restart VSCode
python -m pip3 install discord.py
,-,
Alright
best of luck
is python even added to path?
lol nvm
environment variabes
this if you are on windows

the image smh
igtg, bye
!windows-path
PATH on Windows
If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.
If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).
You can pass any options to the Python interpreter, e.g. to install the [numpy](https://pypi.org/project/numpy/) module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.
You can also access different versions of Python using the version flag of the py command, like so:
C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
Yea installing again is easier tbh
try replit
No please
nice
ik peasants do that but still
@limber isle your code works, but is there any way to do it without throwing an error into the console?
Oh, it does that? I though raising SystemExit would just exit, I forgot how it worked lol
just change raise SystemExit to sys.exit()
@slim lynx
👍🏻
nothing
probably something above it raised the error
what IDE are you using?
show me an ss of the import
yes
your import
that caused the pylance error
ah
try restarting your IDE
I've gotten that error before not sure how it raises though
and you should put commands above your bot.run function otherwise the command won't register into the bot
you will have to
class Close(nextcord.ui.View):
def __init__(self, emoji):
super().__init__()
self.value = None
self.emoji = emoji
@nextcord.ui.button(emoji=self.emoji,label = "Close", style=nextcord.ButtonStyle.red)```
self.emoji not defined
class kick_ban:
@client.command()
async def kick(ctx, member : discord.Member,*, reason = None):
await member.kick()
bot.run(token)
client.run(token)```
Why not wwork
But my some bot command still work
https://paste.pythondiscord.com/qegayesusu.sql what does this mean
what is that, that's not a proper class, you havent passed self, u have 2 .run() functions
why are you making a command inside a class
move it outside of the class
No offense but I suggest you learn a good bit of Python first before attempting the library
You seem to have the gist of it down but there's still some organization you need, such as not having both a bot and a client
that was me
@client.event
async def on_ready():
Print("a")```
Still work
Well yeah
why capitalise p
your internet :^)
i thought discord.py didn't need any wifi to use though
huh
Bruh
.run() needs it
what
How is it gonna connect to the API and the websocket then
or login/connect etc...
the whole point of discord.py is to interact with discord?
What do yoh think bot.latency is?
How to do this work?
😂 i think he's aware?
but how is my wifi a problem though
because you have it off
bot.run('token') thats what they have as their token
class Tickett(nextcord.ui.View):
def __init__(self, emoji):
super().__init__()
self.value = None
self.emoji = emoji
@nextcord.ui.button(emoji=self.emoji,label = "Ticket", style=nextcord.ButtonStyle.gray)
async def tickettt(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
categ = nextcord.utils.get(interaction.guild.categories, id=843120245908176897)
await interaction.response.send_message("Creating a ticket for you, this may take a while!", ephemeral=True)
ticket_channel = await categ.create_text_channel(name=f"ticket-{interaction.user.name}#{interaction.user.discriminator}")
embed=nextcord.Embed(description=f"<#{ticket_channel.id}> - Your ticket has been created")
await interaction.edit_original_message(embed=embed)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)
view=Close()
await ticket_channel.send(f"{interaction.user.mention}")
embed = nextcord.Embed(title=f"Support Needed!", description=f"A ticket opened by **{interaction.user.name}**,\n Server Display name is **{interaction.user.display_name}**\n Support will be with you soon!\, Please describe your problem in the chat!\n The **Close button** can only be used by staffs with manage messages perms!", color=0xFF0000 )
await ticket_channel.send(embed=embed, view=view)
self.value=True``` self not defined in self.emoji but its defined in self.value
or at least that's what i'm inferring
and how do I solve it
turn on your wifi
uh they're talking here doesn't that mean their wifi is on
how do you think im talking here then smartass
you are not connected to internet . or your connection is too slow
from what you said it seems like you had it off when you ran the bot
net issue
re-run the bot
also your token is very pog
hastebin doesn't let me put my bot token in there though
hm
ooi
^^
I'm trying to add a ftp part to my discord bot and was planning on using ftplib (unless you have some better ideas).
ftp = FTP('ftpupload.net') # connect to host, default port
ftp.login(user='USERNAME', passwd='PASSWORD') # user anonymous, passwd anonymous@
ftp.retrlines('LIST') # list directory contents ```
However, I am getting this error.
```Traceback (most recent call last):
File "main.py", line 2, in <module>
ftp = FTP('ftpupload.net') # connect to host, default port
File "/usr/lib/python3.8/ftplib.py", line 119, in __init__
self.connect(host)
File "/usr/lib/python3.8/ftplib.py", line 154, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout,
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
OSError: [Errno 99] Cannot assign requested address```
you did it wrong
Any ideas?
That code isn't going to run
Is there a way to clone a rule, what I actually want to do is to make a role with the same permissions as another role though
in the same server right?
yeah
all the same permissions, channel permissions and guild permissions
basically what i want to do is create a new muted role
create_role takes an permissions arg , so assuming you have a role object role1 already py perms = role1.permissions await guild.create_role(name='new role with same perms' , permissions = perms) will work
Any ideas about my ftp question?
even the individual channel overrides correct?
you would have to loop thru all the guild channels and use py overwrites = channel.overwrites_for(role1) await channel.set_permissions(new_role , overwrites)
can anyone tell me that how to make the bot keep the track of time of a member to join or leaving a voice channel
if you mean how long did the user stay in the vc , when a member joins a vc , cache the datetime.now() object somewhere
and when they leave do it again , on subtracting them you'll get a timedelta object which would be the time
!e py import datetime , time five_secs_ago = datetime.datetime.now() time.sleep(5) time_now = datetime.datetime.now() difference = time_now - five_secs_ago print(difference)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0:00:05.025092
^
yeah I know that we've to use this datetime thing but I wanna know the code. like the code to kno wthat a member joined the vc and left the vc.
so,
for channel in ctx.guild.channels:
overwrites = channel.overwrites_for(role1)
await channel.set_permissions(new_role , overwrites)```
like this?
yea but the await channel.set_perm.... must be inside the loop
ah yeah forgot to press tab there
so that means that discord.Role.permissions returns the guild permissions of a role only, right?
yea its guild specific perm
shield() got an unexpected keyword argument 'loop'
File "C:\Users\admin\Downloads\underdev.py", line 1153, in <module>
bot.run`
bot.run("token here") ...?
yes
send code
where the error occure E
breh that's why send the full code , i can't know just from that
u gonna read full code of 2000 lines?
!!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.
don't u dare underestimate my observation eyes
where link
one sec
k
its already 1 minute
does discord.py support hex codes? like #ffc0cb?
yes
okay thanks
:D
sqlite
@commands.command()
@commands.has_role(MODERATOR_ROLE_NAME)
async def unload(self, ctx, cog: str):
try:
self.bot.unload_extension(cog)
except Exception as e:
print (e)
await ctx.send("Could not unload cog.")
return
await ctx.send("Cog unloaded.")
why is this not working?
indentation
sad, just that?
that was wrongly copied lol
postsgrl
+1 ^
error?
it says cog hasn't loaded
yes its supposed to do that
maybe you're trying to unload a cog that hasn't been loaded :'/
u wrote cog unload outside the try and except
are your cogs inside a folder
yes
hey nobody noticed why are you unloading a cog and the unload cmd is inside a cog 💀
what is the exception?
wait lemme copy the traceback
bruh thats why
provide the full path
help please
where
import discord
from discord.ext import command
also why double
from nexcord.ext import command
and
bot.run(')
must be
bot.run('')
there, try
^unload cogs.gamble or whatever your file name is
oh?
lemme try
bhre ok
- i dont use discord so theres no discord import nd all and double nextcord.exit import commands..ignore that it doeesnt cause and issue and bot.run('') its this only its just that i removed token from hastebin so it wsa mis type issue
Extension 'cogs.gamble' has not been loaded.
this is the exception
u don't use nextcord but u import nextcord? BRAVO
i dont use discord.py*
then load it first, then unload it
typing error man
E ok
its loaded
nevermind
ill take a break now
@prisma spoke can send the error again?
here
k
Uh pull request
?
idk
Nice
and the source says to upgrade aiohttp
fuck
uh word?
pip install aiohttp --upgrade
why don't use discord.py lol
it sucks
k, np
why...?
danny
oh, not working on it anymore? (it still work tho)
it worked
but one more error
hmm what is it
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\nextcord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "c:\Users\admin\Downloads\underdev.py", line 103, in on_command_error
raise error
File "C:\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1004, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 887, in invoke
await self.prepare(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 821, in prepare
await self._parse_arguments(ctx)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 727, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 579, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "C:\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 1182, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 1076, in _actual_conversion
return await converter().convert(ctx, argument)
File "C:\Python310\lib\site-packages\nextcord\ext\commands\converter.py", line 798, in convert
raise EmojiNotFound(argument)
nextcord.ext.commands.errors.EmojiNotFound: Emoji "🦷" not found.```
Because dpy is slowly becoming more and more outdated and left behind
class TicketButton(nextcord.ui.Button):
def __init__(self, emoji):
super().__init__(emoji=emoji, style=nextcord.ButtonStyle.gray, label='Ticket')
async def callback(self, interaction: nextcord.Interaction):
await interaction.response.send_message("hello")
class Tickett(nextcord.ui.View):
def __init__(self, emoji):
super().__init__()
self.add_item(TicketButton(emoji))
@bot.command()
async def t(ctx,emoji:nextcord.Emoji=None):
await ctx.send("h",view=Tickett(emoji))```
Dpy doesn't support slashes, soon, modals are coming, and dpy won't have them either
modals? what are those
ow ok
Use .PartialEmoji
Text inputs
o
o
!d nextcord.PartialEmoji
class nextcord.PartialEmoji```
Represents a “partial” emoji.
This model will be given in two scenarios:
• “Raw” data events such as [`on_raw_reaction_add()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.on_raw_reaction_add "nextcord.on_raw_reaction_add")
• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Message.reactions "nextcord.Message.reactions")...
O
@slate swan
nextcord.ext.commands.errors.PartialEmojiConversionFailure: Couldn't convert "🧰" to PartialEmoji.```
why tf has it gone to nextcord
nothing is gone though
partial emoji only supports custom emojis and not unicode ones
Right
then how to solve that....
I have no clue which one supports the unicode ones ngl
do u have a bot?
Yes ofc I do
nme?
I don't have any public bots
ij -
does anyone know why pycharm slowdown my pc
because it consumes too much ram
use sublime
Get a better pc
@bot.command()
async def clone(ctx, role : disnake.Role):
new_role = await ctx.guild.create_role(name="Altmute")
for channel in ctx.guild.channels:
overwrites = channel.overwrites_for(role)
await channel.set_permissions(new_role , overwrites)
This says set_permissions take 2 positional arguments but three were given?
u right ||my pc even not responding when i open MS paint||
how much
isn't it the same?
I use pycharm community and my pc isn’t slowed at all so
!d discord.TextChannel.set_permissions || overwrites=overwrites maybe? gotta check docs
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
ask your task manager
And I’m running like tons of stuff
depends on your ram
whooops
My pc isn’t like that great, I have 4096gbs of ram or smth
no, sublime is way lighter than pycharm
thats the memory your main.py is taking , not the pycharm application
Copy paste the traceback
🙂 wait what the
check task manager lol
sup @quick gust
your token.
oops
the error or the code?
@bot.command()
async def clone(ctx, role : disnake.Role):
new_role = await ctx.guild.create_role(name="Altmute")
for channel in ctx.guild.channels:
overwrites = channel.overwrites_for(role)
await channel.set_permissions(new_role, overwrites=overwrites)
how do I add a cog_check method into my cog? ```py
async def cog_check(self, ctx):
return ctx.guild.id == 880030618275155998
nice, it's so light, now where is terminal and run button?
ctrl b i think
or ctrl shift b
those two are same and it's not terminal
ctrl + b for build ,
ctrl + shift + b for build with
sublime wont open it in terminal
eh...?
it has an inbuilt terminal like build
where all prints will take place
or just use python <file path> in your terminal
umm where run button (and can i pip install there?)
in your device's terminal
uh what
the run button is ctrl + b , and use your device's terminal for pip installs
ever saw something like "command prompt" in your device?
ow (i already pip install 2 times, but why it says no module E)
oh that thing, yes yes
use it..
ow ok
I was wondering how do bot devs create image form of leaderboard
like for example this
any guides/tutorial links?
...
ohh
and some maths
maths? 0--0
oh i see , its because sublime is not using your python environment
what the
kinda as weight as pycharm in my pc ;-;
oh i see , it allows you to choose the python environment you want to use , idk how to set that in sublime
you can ask in #editors-ides how to do that
ok, thanks
Hey @prisma spoke!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/nextcord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/container/TRX.py", line 780, in on_command_error
raise error
File "/home/container/.local/lib/python3.10/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.10/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: DownloadError: ERROR: Signature extraction failed: Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/youtube_dl/extractor/youtube.py", line 1348, in _decrypt_signature
func = self._extract_signature_function(
File "/home/container/.local/lib/python3.10/site-packages/youtube_dl/extractor/youtube.py", line 1262, in _extract_signature_function
res = self._parse_sig_js(code)
File "/home/container/.local/lib/python3.10/site-packages/youtube_dl/extractor/youtube.py", line 1331, in _parse_sig_js
initial_function = jsi.extract_function(funcname)
File "/home/container/.local/lib/python3.10/site-packages/youtube_dl/jsinterp.py", line 245, in extract_function
raise ExtractorError('Could not find JS function %r' % funcname)
youtube_dl.utils.ExtractorError: Could not find JS function 'na'
(caused by ExtractorError("Could not find JS function 'na'"))```
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
It's not a point, you can use it and doing what you want but we cannot help you due to the youtube Terms Of Service, you have to solve it by another way
if it does then what shud i use?
There is no package who follow that rules, there are some particular case for example a public research but you need a sort of license i think
Don't make music bot streaming from YouTube.
then?
We can't provide you a solution, that's the fact 😆
Don't let people find out that your doing it, and do it yourself, because asking people for help is basically letting people know what you're doing
Easy
¯\_(ツ)_/¯
but i need a solution tho
soo i need to come.
Then find the solution on your own, we can't help with that
wait a minute, YTDL is exist??? wow
always did
Damn my bot reached 97 servers
Both