#discord-bots
1 messages ยท Page 476 of 1
The statuscheck file, which I assume is the first one, is a blocking file. It has an infiinite while loop, that it never breaks from. Once you import the file, it will never continue past that import

Yeah I realized that a while back, right now I'm just seeing if they work together, which they don't lol
And yes, it's the first one
You're going to want to modify your code a bit to use non-blocking loops so that they run at the same time. You can use discord.py's task system for this
Ohhhh, I see what you're saying. The while loop never lets the bot function run at all. It never gets passed it
the time.sleep also will cause an issue should you decide to use tasks
If you decided to use tasks, switch to asyncio.sleep
but the tasks should take care of looping and intervals for you
Gotcha. I'll start reading up on it. Thank you
@wicked atlas is "pip install python-dotenv" the right one?
Yes, that is the name of the dotenv module
hey how do you make a fun fact bot
it will choose a random message from the list that i will put??
yes an api
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ext.context import Context
# the command
@commands.command()
async def invite(self, ctx: "Context", member: discord.Member) -> None:
...
```so the problem here was
```py
self.params[key] = value = value.replace(annotation=eval(value.annotation, function.__globals__))
File "<string>", line 1, in <module>
NameError: name 'Context' is not defined
```it seems that I cant use import in `typing.TYPE_CHECKING` for type hinting `Context`?
the discord.py Context object should be imported like this
from discord.exts.commands import Context
Or, you can use it like this
from discord.exts import commands
ctx: comands.Context
*I used my custom Context
I believe you might have an error though, since you are using self, but it looks like it's outside of a class
nah, it's just to show the command
i have a long class tho
that's why I dont include it there in my code
can someone please help me?
it wont send the Hello! in the server after i type !hello
okay first of all you havent set a server prefix, which you must do
uhm...how?
second of all, your if message.content.startswith('!hello'): is at the wrong indentation level
okay so bring it back one?
uhh go search google! or stackoverflow
yes
have you tried it in a server? to test if it works?
mhm!
does it just not print anything?
okay goodjob!
i just tested it like 5 seconds ago tho- maybe lag?
make a ping command to find out
repl it is laggy
^
just remember to set a server prefix in the future so that it will be easier to code in the future, and for other reasons
speaking of which, you might have to migrate so slash commands to make it worse
hey can someone help me with making my fun fact bot? like i want it to choose from the list i will pput
hi! you can use a fun fact module, which i use :)
oki
you can also import random
thats if you are using replit
im pretty sure
i only use replit so i dont know
yes, but tbh please dont use fun fact lists HAHA imo they're either very laggy or do not have much facts
especially if you have a few hundred items in ur list
yeah facts
you do know how to install ur own modules using repl.it's package manager, right?
I wouldn't suggest using discord.Client use discord.Bot
sorry sorry
at this point it works thank you
but the issue is it only appends the message straight after the command, nothing after it that has spaces
i have 4 days experience with replit but i think
u just
go to the um side bar i think its called
then you just search
You would have to use a * in the parameters so ctx, *, newitem
The star will make it read everything after the command as newitem
Help regarding dc.py
class graph_multi(commands.Cog):
"""The description for Bargraph goes here."""
def __init__(self, bot):
self.bot = bot
@commands.command("!bar_multi")
async def bar_multi(self, ctx, title: str, xl: str, yl: str, data: str):
dbg = graph()
data = data.split("#")
ng = len(data)
for i in range(len(data)):
data[i] = data[i].split(",")
keys = []
values = []
for i in range(len(data)):
keys.append([])
values.append([])
for i in range(len(data)):
for n in range(len(data[i])):
if n % 2 == 0:
keys[i].append(data[i][n])
else:
values[i].append(int(data[i][n]))
if len(values) != len(keys):
await ctx.send("The amount of keys and values are not the same")
else:
print(keys, values)
dbg.barGraph(keys, values, title, xl, yl, ng)
await ctx.send(file=discord.File('mygraph.png'))
def setup(bot):
bot.add_cog(graph_multi(bot))
So i have this cog setup but its giving me this wrror
discord.ext.commands.errors.CommandNotFound: Command "bar_multi" is not found
And this is the bot code
from discord.ext import commands
import config
bot = commands.Bot(command_prefix="!")
bot.load_extension("cogs.graph_single")
bot.load_extension("cogs.graph_multi")
bot.run(config.TOKEN)
you don't need to put the prefix in the command name, and iirc its @commands.command(name="bar_multi") not just @commands.command("bar_multi")
@red kraken can you help me with the code for making a fact bot?
oh yeah i am so blind
thanks for the help
currently working on this bot so rn i cant
Find an api and try using it
np
ok
How can I get the title of an embed message if I have the message object?
!d discord.Message.embeds
A list of embeds the message has.
Use that
thanks
Use Embed.title attribute for getting the title
message.embeds[0].title
How would one do a tempban system? ๐ค
Like, what components would I need? I know I'd need the mentioned user and a role to slap on them that 'mutes' them.
the part I need to figure out is, the 'temp' part.
ideas?
A database to store the time of unban, member.ban, member.unban, tasks.loop, await send
It isn't efficient at all
Why not?
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
I ran a quick test and it doesn't stop the bot from receiving more commands
Yes it doesn't, but it's still not the best
It just isn't
you don't load it with the class name, load the file name, example the file name is GraphMulti.py, you do bot.load_extension("cogs.GraphMulti")
hey uhm i have a code that sends Hello! whenever someone says !hello right? but i wanna be able to run multiple commands anyone happen to know how to do that?
are you using discord.Client?
!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/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
This is what we use as a command handler
You define async functions as commannds
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.
Here's a tutorial to go through
okay
thanks!
for now though can you run me through this person to person?
how would i use the command to make this run multiple commands?
can anyone help me with the code for the fact bot i want? please?
@bot.command() #this is the decorater
async def ping(ctx): #this is defining the command name and thea arguemnts in this case it is only ctx (Context)
await ctx.send("Pong") #this sends "pong" to the channel the command was invoked in
okay
so by using this
whenever the bots command that i put gets typed into the chat
it will send Pong?
yes i can see just by looking
if you command prefix is !
And you do !ping it will send pong
THANK YOU SO MUCHHHH!!!!!
@rough flicker first time?
same but i started 4 days ago so i know a bit
No problem also if you want you can read this https://vcokltfre.dev/ it's useful
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.
how could i set that up?
this is my first ever thing i put into the bot
@client.command(aliases=["Ping"])
async def ping(ctx):
await ctx.channel.send("Pong!")
memes from where
anywhere really
case insensitive=True in bot constructor
just a random meme generator
!d discord.ext.commands.Bot - all methods and attiributes for it
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/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
walk me through it please?
Press the hyperlink
anyways....
you mean the bot will send random facts?
are you going to be writing some facts down or using requests to get them?
yes
im gonna write
okay so
import random
#bot construction
async def fact(ctx):
facts = #put your facts in a list here
random_fact = random.choice(facts)
await ctx.send(random_fact)
I a server owner and im making a music bot for it..the bot works..i need 3 such bots...so i wanted to ask that can i run 3 bots from 1 single code ?
im dumb but i dont think so
lol alr
@commands.command()
@commands.has_any_role('bot','Bot','Owner')
async def tempmute(self, ctx, member : discord.Member, length = 60):
senderrole = ctx.author.roles
targetrole = member.roles
guildroles = ctx.guild.roles
senderroleindex = 0
targetroleindex = 0
for i in guildroles:
for a in senderrole:
if a == i:
if senderroleindex < guildroles.index(i):
senderroleindex = guildroles.index(i)
for a in targetrole:
if a == i:
if targetroleindex < guildroles.index(i):
targetroleindex = guildroles.index(i)
if senderroleindex > targetroleindex:
await ctx.send(f"Muted: {member.mention} for {length}seconds.")
await member.add_role("test")
elif senderroleindex == targetroleindex or senderroleindex < targetroleindex:
await ctx.send("Cannot mute someone with the same or greater role than you.")
What am I doing wrong? I can't seem to add the role to the mentioned user.
it works ty diabloical
maybe member.add_roles
Cz it is member.add_roles
??
Yes, u can but they won't work properly tbh
do i have to get the role ID instead?
add_roles wants a role object as parameter, not just a string
oh how ? and like what would be error
Well not error, but they would just lag a lot
gah so now I gotta get the "mute" role ;-;
so i like hace repliut premium so if i boost them would decrease the lag ??
Sort of...
alr good for me how do i do it ??
no lol say more and tell me why u think so...like idk i havent faced any issues ig..
There u go. A big tag warning
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. *Including you.
Understand, donโt memorize.
But yea, it's worth reading it
Well, never used premium sooo idk
Make multiple bot instances
Bad practice and looks bad
Make separate project in different folder
oh but like i only space for 1 more boosted replit so only 1 project...seperate cogs ??
how does big bots who do premium bots and custom bot looks do this ?? the code is space..only the bot is changed
how do they do this ??


alright now to make a database \o/
hey @spring flax when I put something random like bear in the code u sent it said bear was not defined. do u know how to fix this?
Code?
Can i see it what you have
alright can u wait 2-3 min? im getting called
Sure
They must be strings
You haven't defined any of these variables
["blah", "blah", ...]
The bare minimum of python knowledge is required
with?
my chat bot can take 1 word commands such as fine or bad right?
but i want it to be liek !im fine not just fine
cuz the input method is !fine not !im fine
what
Make a command group
and i dont know how to set up multiple word commands
wdym? like if i say !hi the bot can only say Hi?
look
i dont get it
Read the error , also if you want to make your commands case insensitive , use case_insensitive=True in commands.Bot instead of using aliases
ok
ill set it like that
so u can only do
!hi and not !hi hello
is that what u mean?
oh
How about just dropping the prefix and just reply based on message content. And set a channel where the bot can only answer.
mhm! cuz i want it to be a realistic chat bot
OH BIG BRAIN
HOW DO THAT I?
please tell me?
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
okay so .. now im thinking do you think if i set it so that you have to say demelos (the bots name) then the messege and i set replies to what you say .. it will work like that?
read how this event works
why is command not found?
@commands.Cog.listener not event
I see thanks
how can i make it so an argument requires a link
Make a custom converter that checks with regex if the cpntent of the arg is a link
csnt i just do if "https://" not in icon
No because then someone could just send hellohttps://hello
You can do
if argument.startswith("https")
But I suggest NIR's way
The hardest part is regex I guess
But better
And that's why there are already pre-made regex
by using commands.MissingRequiredArgument is there a way to tell what argument i'm missing?
!d discord.ext.commands.MissingRequiredArgument it is in the docs
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
Ptobably param
Dude, I had almost written it all
alright thanks
on_hunder_sad
Indeed
Which IDE do you use?
Vsc i guess
Yea, seems like it, but see the way the IDE is showing error... I don't know how that happened
maybe extension
I want to know which one haha
hlo
i know improper token but i gave it a correct token i swear
i even changed applications
hey guys i am a beginner in bot making and am stuck in my code so can someone pls check my error and help me?
create new token
and try again
@slate swan can you help me with my code pls?
YES
im using visual studio.
ok
extension for errors?
Ah, ok
VS, not VSCode haha
Oh
Been busy figuring out how to do this db crap in python xD
show your problem and someone will help
My current issue is: figuring out how to convert a string that represents a datetime into a datetime xD
Haha!
Good luck
Remove ' ' from bot.run
from my bot
ok
bot.run(TOKEN)
ok lemme try that
So I've setup my command to tempmute someone.
setup my auto loop.
setup my database. Now for the fun part \o/ unmuting someone lol
Just remove 'token' and run likr this,bot.run(TOKEN)
does nothing
i was testing my bot on replit because when i tried to host my bot on heruko my bot did not go online
are you sure you pasting token ? and not the client secret?
oh oki
most probably because you didn't load the cog?
Also yr indent bro
Yea?
It is python not Java script
When did I say it's js...
why it gives an error?
@client.command()
async def emoji(ctx, emoji: Union[discord.Emoji, discord.PartialEmoji, str]):
"""Post a large size emojis in chat."""
if not isinstance(emoji, str): # if it is a custom discord emoji
d_emoji = cast(discord.Emoji, emoji)
ext = "gif" if d_emoji.animated else "png"
url = d_emoji.url
filename = f"{d_emoji.name}.{ext}"
else: # use the twitter emoji api
try:
cdn_fmt = "https://twemoji.maxcdn.com/2/72x72/{codepoint:x}.png"
url = cdn_fmt.format(codepoint=ord(str(emoji)))
filename = "emoji.png"
except TypeError:
return await ctx.send("That doesn't appear to be a valid emoji")
try: # read it with BytesIO so you dont need to save the image
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
image = os.BytesIO(await resp.read())
except Exception:
return await ctx.send("That doesn't appear to be a valid emoji")
file = discord.File(image, filename=filename)
await ctx.send(file=file)```
In py there I no intents
from typing import Union
Also don't copy code from next time
Bro.....?
Nothing my bad leave
-> There are intents in Python also ๐คฆ
-> I wrote indents, not intents
just add
import Union``` ?
Haha it's fine. I just wanted to tell them that the indents are off
Yes sorry
from typing import Union
Also don't copy code please
error again
d_emoji = cast(discord.Emoji, emoji)
error
most likely because you didnt import the library cast is from
?
What's the problem? I don't understand that language, sorry ๐ ๐
es espaรฑol creo
English Please
but itโs just saying a invite was deleted and who the owner the invite is and how many uses
Ah
i believe they are not getting the owner nor uses which is the problem
Do u have intents?
Could be they don't have the intents
!d discord.Intents.invites
Whether guild invite related events are enabled.
This corresponds to the following events:
This does not correspond to any attributes or classes in the library in terms of cache.
most likely
ohh, i see, thank u guys
(:
hey, so im starting to learn how to split code into mulitple files without the use of Classes, but this type of error keeps happening:
bot not defined, any tips?
define bot
!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/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
no i did
code?
yeah but you cant define bot from another file
this is the event_end.py file
async def event_end():
code```
ok what i sent dont really help out muich
Hey guys im having a problem with the bot joining the voice channel im in. It sends an error and doesnt join. Could someone help me?
any tips tho?
What's the error....?
use cogs ig? They're python classes too
Did you install discord.py voice support?
is it possible if u give me this? im sorry
is it possible for a command to have a diff prefix from the other commands?
i searched but didnt find anything
i dont think its possible
maybe change it to channel = ctx.author.voice_channel
hey guys i am learning how to make a discord bot so that it shows the current time....its working but can someone help me to change its timezone?
may i see the code of this? im curious
it sounds very intresting
ncc
i need help tho
now this comes up
ctx.author.voice.channel
ctx.author.voice.channel
It's not a discord bot related question , but anyways...
How can i activate those parallal lines in vis. studio code?
may i use this?
if you mean copy pasting the code then yeah i dont mind
nice
lol
so yeah
can you help me?
still the same errors
Can't be
in what
so where can I copy and paste or do i have to write it down myself?
Ah its a different error
oh ok
i made a bot so that it shows the current time but i want to change the timezone
!d datetime.datetime()
@spark estuary
Get the voice channel object and do vc.connect
yes lemme copy pasta
new_message = datetime.now()
currentTime = new_message.strftime("%H:%M:%S")
if message.content.startswith('$time'):
await message.channel.send(f"Time{currentTime}")
tysm :>
^^
i tried may keywords but failed
anyone else use vsc?
tz' and what not
@spark estuary i tried copying and pasting then writing it down but it still gave me an indentation error
If you're trying to show the current time then there is an attribute for messages
created_at
it means that smthngs wrong with the spacing
hmm
put a apace after if
hi! is there any way to edit a message while preserving its original attributes?
for example, if i wanted to change the content='' argument, i would pass it in the discord.Message.edit() method, it would change only the message in the content attribute (leaving any other attributes, i.e embed, file, etc. untouched from the original message instead of resetting them).
It u edit content, it will only edit the content, not the embed
Just tried it
ohh, right, tysm for the help
im not sure since how long its been that way, i couldve sworn it used to reset the whole thing, or maybe i am just being forgetful again haha
Ah, I also used to think it would remove everything, but seems like they updated it or something
yeah same, either way thanks a lot i really appreciate it
(:
What your import looks like?
If it is import datetime
You should write yout first line as new_message = datetime.datetime.now()
def check(m):
return m.content == ['yes' , 'no']
message = await bot.wait_for('message', check=check)
if m.content=='yes':
await ctx.send("ok")```
why doesn't this work
cuz message.content will never be a list
i think you meant in rather than ==
(check function)
hm
wym
oh
i will do that
def check(m):
return m.content in ['yes' , 'no']
message = await bot.wait_for('message', check=check)
if m.content=='yes':
await ctx.send("ok")```
so this should work
it does not work
@hasty iron
then define it
if its in a cog then self.bot
ok
my code seems to be running without any errors, listener is working but not commands
anyone know what could be the reason?
nvm i deleted the process commands line
hi? how do i get the id of the button clicker -- discord components
Hey i wanted to make a command that my bot sends the same message every 2 hours ive been researching how to do it but i didnt get it my only "working" command is sp!reminder "text" and he will send it everytime and i dont really want it to be like that so if someone could explain me how to do that it would be very nice! Thanks
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
This would help ๐
Hw do I print my discord.py or python version?
discord.__version__ <-- discord.py version
thanks
sys.version or platform.python_version() <-- Python version
how do i create a category at the end of all caterogry's
is there any good youtube lib for discord?
youtube_dl?
is making a bot to spam 5 spam channels at the same time against tos??????!?!!?
its my server and my spam channels
5 minutes of spamming later....
๐
Well, if its your server and your channels you should be able? But Iโm pretty sure as long as it doesnโt affect anyone else you should be fine ๐
goog
anybody know how to print a unix timestamp using python kek
why??????????????????
That's API abuse for sure
is it icon_url=url or icon.url=url in 2.0?
It's like member.avarar.url, guild.icon.url
so icon.url=member.avatar.url?
hm
stop posting about it here

about what

we don't support or discuss about something that breaks ToS of any platform
how do i know that my bot has been invited to a server
i want to create a channel in the server bot has invited to
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
okay tysm
is it possible to create a share to discord button? kinda like whatsapp here https://wa.me/whatsappphonenumber/?text=some-message
does anybody know how to make a bot send a unix timestamp?
i tried await ctx.send (int(time.time()))
i get a 404 page from that link
there are multiple ways
how do i make a category as the last category's of the category
is buttons and gui elements available on discord.py?
ur just not using it
Whats the pip?
oooh
hi
pip install discord.py
that's only for stable
pip install -U git+https://github.com/Rapptz/discord.py
for 2.0 (master branch)
why doesn't this work
@commands.Cog.listener()
async def on_guild_join(self, ctx):
await ctx.guild.create_category('Mailer')```
what doesn't work?
this ^^
and what about it doesn't work?
no error
do you have Intents.guilds?
i reinvite my bot
didnt work for me its just saying "[pyflakes] invalid syntax"
that's just priviledged gateway intents in the portal
i'm asking if you enabled guilds intent which isn't priviledged
im hosting my bot in heroku but im getting this error:
File "/app/main.py", line 1, in <module>
app[worker.1]: from core import *
app[worker.1]: File "/app/core.py", line 1, in <module>
app[worker.1]: import discord
app[worker.1]: ModuleNotFoundError: No module named 'discord'
how do u make a button in it tho?
how can i install discord module in heroku
master branch doesn't have components support
do u have requirments.txt
yes
requirements.txt and procfile
shouldn't have used heroku
oh am i supposed to list the modules in requirements.txt
@valid niche
heroku is just straight up horrible
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client").
New in version 1.5...
i am actually hosting mine over there
stop
yes i also did that
add the print statement in the on guild join and trigger it again
ok
thanks
read this @stark bobcat
it's very bad
well what else do you recommend
tho it's dirt cheap like at most a coffee a month
a decent VPS, there are hundreds of services and all you need for a discord bot can fit in a plan of just a few bucks a month
literally a coffee a month would be enough for most
or a raspberry pi if you're more into a one time purchase
ohh
here is a list of some of the most well known worldwide hosts
I have this "jishaku" cog and I want the bot the remove that cause it doesn't look nice. How do I do this?
okay idk what on earth is wrong with replit, but this keeps happening:
running on local has no problems, the bot runs successfully and theres no error at all
how can i make my bot dm user who just joined? Or added him to a server?
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
jishaku has a command to hide it
that is?
not everyone is rich or even has money
use the help command
and i dont even have that line of code
Which one
whats your bots prefix?
NVM
found it
ok
@slate swan
wat
.
it may be a error in the lib
can I hide this or no?
probably
wdym
aight
async def _loop(self, ctx: commands.Context):
"""Loops the currently playing song.
Invoke this command again to unloop the song.
"""
if not ctx.voice_state.is_playing:
return await ctx.send('Nothing being played at the moment.')
# Inverse boolean value to loop and unloop.
ctx.voice_state.loop = not ctx.voice_state.loop
await ctx.message.add_reaction('โ
')
``` guys my loop is not working any fix?
the error might be caused by the lib
O.o
but then i did
pip install discord
pip install discord.py
pip install poetry
pip install --upgrade pip
```and updated everything
Where is the arg missing?
@bot.command(aliases=['e'])
async def enchant(ctx, arg):
rarities = ["Normie",
"Good", "Great", "Mega", "Epic", "Hyper", "Ultimate", "Perfect", "Edgy", "Ultra-Edgy", "Omega", "Ultra-Omega", "Godly"]
embed = discord.Embed(title="", description="You've enchanted your sword for 3,000 coins", color=0x109319)
rng = random.choice(rarities)
embed.set_author(name="CEO", icon_url= "https://i.imgur.com/jszzFTz.png")
embed.add_field(name=f"โจ ~-~> {rng} <~-~ โจ", value="You've enchanted your sword for 3,000 coins", inline=False)
await ctx.send(embed=embed)
error?
arg is a required requirement which is missing
any idea?
remove the arg param
u dont even need it lol
you using the original or a fork of dpy?
original
thats the problem
its fine running on local, but when i did on replit, it shows that
and last time theres also this error
If is a required requirement which is missing comes up you probably forgot or didn't type in the command correctly
running on local is fine
stap pinging i just want to code in piece ๐ข
i dont think u can do that yet
is there a Message.type of a spotify listen along invitation?
see this : https://discord.com/users/887382207189110856 it wont work for me
for this to work should the user need to be Cached for me?
what
guys task loop stop working how can i fix it ?
i have a quiz bot which uses the wait_for function, and wanted it to allow only one quiz at a time, but how can i implement that? https://hastebin.com/ejeyirecom.py
solved
import asyncio as l
import discordSuperUtils as i
import time as q
p = print
g = q.time
z = l.sleep
s_ = i.SpotifyClient
c_ = i.YoutubeClient
async def j(c, a):
b = g()
v = await c.get_query_id(a)
p('searched in', g() - b)
s = g()
b = await c.get_video(v)
p('got video in', g() - s)
if 'streamingData' in b:
return b['streamingData']['adaptiveFormats']
async def r():
c = c_()
s = s_(client_secret="MY TOKEN", client_id="ANOTHER TOKEN")
a = await s.get_songs('MY PLAYLIST')
p('started')
start = g()
o = await l.gather(*[
j(c, t) for t in a
])
p(g() - start, 'end')
p(len(o), len(a))
p(o[0])
await z(5)
await c.session.close()
l.run(r())
hi guys please help me whats wrong with my code??
whats the error
I think you are in wrong channel
i do not understand coding why cant i just become rich without code
rely?
What are you trying do?
i dont know myself actually
well whats the error of your code
How can help then? ๐
or is there no error meessage and it just doesnt work
ye men thats the case pls help i need to complete this!!
well this doesnt seem like its a disord bot, so i think Tsekis was right, so i cant tell what you were trying to do with your code
so what is this supposed to do?
uhh
idk
so you got code from the internet and dont know how it even works?
or wtf are you doing that you got code which you have no idea of how it works, what its supposed to do and is hard to read due to bad var naming
i found no client event on the docs to check for that but there might be sth else
discord.on_user_update(before, after)
Called when a User updates their profile.
This is called when one or more of the following things change:
avatar
username
discriminator
This requires Intents.members to be enabled.
Parameters
before (User) โ The updated userโs old info.
after (User) โ The updated userโs updated info.``` i found this tho
This function is a coroutine.
Requests previously offline members from the guild to be filled up into the Guild.members cache. This function is usually not called. It should only be used if you have the fetch_offline_members parameter set to False.
When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if Guild.large is True.
This method is deprecated. Use Guild.chunk() instead.
Parameters
*guilds (Guild) โ An argument list of guilds to request offline members for.
Raises
InvalidArgument โ If any guild is unavailable in the collection.``` Found sth!
that thing might work
you need to get the guild, get yourself, and then you should be able to canstantly check if youre in there and werent before
ok
you are like a passanger who asked the driver to drop you somewhere
https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.request_offline_members this is the link to the section in the docs if you need
if you want us to help, we want to know your destination
the first thing that scared me was the imports ๐
code readability and proper variable naming comes at very high levels. but the purpose of the code?
no its good

have you figured out what that code is doing?
or what you want to do?
no man it was a joke
what is the context here
i wrote it!!!
tsekis more like sekis
@hasty iron he jsut did this "joke"
its a good script dont even lie bro
what even is that
sometimes when people fuck things up they just try to justify it as jokes
i just wrote some youtube client
if youโre trying to be esoteric thatโs not how you do it
I've done it personally I think
yeah, you use lambdas
well wheres the youtube thing i only saw a spotify thing
oh there are both
read my code ๐ 
and use asyncio.coroutine to make the lambdas coro 
ytdl is pretty poop for discord bots
my youtube client fetches 500 players in like 10 seconds instead of 2 mintues on ytdl
ok
didnt that one popular ytdl music bot got shut down lately
youtube now cares about breaking of their tos
what is the equiv of bot.get_message (like bot.get_channel etc)
you mean something that gets you the message?
bot.get_emoji?
what
await channel.fetch_message?
if so you can filter Bot.cached_messages or use TextChannel.get_partial_message/fetch_message
i wish get_all_channels was a dict
why
generals = bot.get_all_channels()['general'] and it returns a list of all general channels
i can make it but i really cant be fucked rn
that sounds like a very dumb idea
having keys consisting of anything other than ids is inconsistent
considering that the whole library caches based on id
and also doesnโt that return an iterator?
like the actual thing
!d discord.Client.get_all_channels
for ... in get_all_channels()```
A generator that retrieves every [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") the client can โaccessโ.
This is equivalent to:
```py
for guild in client.guilds:
for channel in guild.channels:
yield channel
``` Note
Just because you receive a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") does not mean that you can communicate in said channel. [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for") should be used for that.
you can just filter whatever you want from that
you can filter it
@manic wing what's your end goal?
i dont need help lol, i was just mulling it over
hey can anyone help me with making the code for a fact bot where I don't have to write the facts 1 by ? please tag or dm me ๐ tysm
How can I target messages from a specific user?
hi does anybody know how to only allow a user with a certain role to use a command?i need to do that for my eval command
use the kwarg "name"
wym
alright tenks man
works for me idk why urs dont
hm
show ur on_guild_join maybe?
i am using on_guild_join
hey there!
im getting this track recently. someones knows?
uh ye
yes show me the code
ok
sometimes its works but sometimes not
@commands.Cog.listener()
async def on_guild_join(self, ctx):
await ctx.guild.create_category('Mailer')
print('test')```
on_guild_join only takes guild not ctx
oh
and why **'Mailer'?
ok thanks lemma try
sorry I didn't know it was an event
someone?
it will error because Mailer is not a mapping
hmm
mapping?
ok thanks
please?
.
@lament mesa
@commands.Cog.listener()
async def on_guild_join(self):
await guild.create_category('Mailer')
print('test')```
why is there an indent at async def btw
???
becuz its in a cog
no the code i sended was like that
Show code @slate swan
async def on_guild_join(self, guild)
that should work
its take my to there
@slate swan
pls
Maybe use an api
use an api
ok
on the tracks =
ok let me try
!pypi randfacts
You can also use this REST API: https://fungenerators.com/api/facts/?ref=apilist.fun
doesn't work
is async def on_message(ctx, message): if message.attachment and if ctx.channel.id is 887626373991120946: await message.add_reaction("๐ฉ")
correct?
async def on_message(message):
if message.attachment and message.channel.id == 887626373991120946:
await message.add_reaction("๐ฉ")
``` this is correct
Thanks
thankss
someone?
quick question how can I get the most recent message id?
specifically the most recent 100
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/stable/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
defaults to 100
There's a large issue facing all discord bots, especially those using discord.py and similar, that could lead to all of those projects dying.
I want to spread the word, and have users fight back against this. I made a petition against the decision (effective april of 2022) http://chng.it/4gZpLmW5vJ
Please consider making your voice heard.
seems fishy
???
msg = message.content @client.event async def on_message(message): if msg.startswith("-hello"): await message.channel.send("Hi")
Whats wrong with msg variable?
how i make my bot say something in the server as they added it?
with the message_purge method, do I need to setup to need manage permissions
or will it automatically have it
You can either send in the guild.system_channel or get a random channel from the guild.text_channels and send in it.
!d discord.Guild.system_channel
system_channel```
Returns the guildโs channel used for system messages.
If no channel is set, then this returns `None`.
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3.10/library/exceptions.html#IndexError "IndexError").
well, even if you make a petition there is probably a 0.1% chance discord will take action in any way
what if multiple channels?
๐ฆ
do I use a dictionary?
use a list
how to get current channel id?
i would just get multiple channels like
c1
c2
c3
and do stuff
one a mesage was sent in
ctx.channel.id
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
then use message.channel.id
if message.content.startswith(f"{prefix}delete"):
await channel.purge(limit=1)
await message.channel.send('Deleted {} message(s)'.format(len(deleted)))```
channel on line 2
why not use commands
yeah
then events arent your best way to go
!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/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
is it safe ?
new module?
No. They'll steal your identity.
@bot.command()
async def yourcommandnamr(ctx):
await ctx.send("yes")
```bot or client depends on what you set it as
uh no
dude
Just an extension to discord.py
what is an extension
he's kidding lol it's perfectly safe
I meant it might run some programs in background
did you get enough oxigen?
uh
discord.py: #the parent
discord.ext.commmands # the submodule
``` :)
lol Several people
again
been using this all of 10 minutes
if there is some tutorial I can follow
oh submodule got it
yes
I'm just kidding. Also it's safe, yes.
It's on Pypi so it's safe. Also they have a link to the source code.
any other similar libraries ?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.command(name = "setxp")
@commands.is_owner()
async def setxp_command(ctx, amount : int = 10, user : discord.User = None):
if not user:
cursor = expstorage.cursor()
cursor.execute(f"UPDATE expstorage SET userxp = {str(amount)} WHERE client_id = {str(ctx.message.author.id)}")
expstorage.commit()
embed=discord.Embed(color=0x01e418, description = f"Set `userxp` = `{amount}` for {(ctx.message.author).mention} !")
await ctx.send(embed = embed)
return amount,user
elif user:
cursor = expstorage.cursor()
cursor.execute(f"UPDATE expstorage SET userxp = {str(amount)} WHERE client_id = {str(user.id)}")
expstorage.commit()
embed=discord.Embed(color=0x01e418, description = f"Set `userxp` = `{amount}` for {user.mention} !")
await ctx.send(embed = embed)
@setxp_command.error
async def setxp_command(ctx, error):
if isinstance(error, commands.BadArgument):
embed=discord.Embed(description = f'''
{(ctx.message.author).mention} | Invaild Command !
*Your previous command :
''', color=0xf50a0a)
await ctx.message.delete()
await ctx.send(embed=embed, delete_after = 5)
elif isinstance(error, commands.NotOwner):
embed=discord.Embed(description = f'{(ctx.message.author).mention} | You aren\'t this owner bot !', color=0xf50a0a)
await ctx.message.delete()
await ctx.send(embed=embed, delete_after = 5)
how can i get the command that user used bcz i want to print it again in error
i'm not sure why it says i am lacking perms when my id is 727484628486848552
@client.command()
async def ownertest(ctx):
if ctx.message.author.id == ('727484628486848552'):
await ctx.send('weifjousdibh')
else:
await ctx.send('you are lacking perms')
IDs are ints not strings
<your context>.command.name
Your ID is an integer and you are using a string.
ext commands
ctx.command.name
oh ok tenks
int("yourid")
also just use ctx.author.id

use a check instead of that
yes , if you use (ctx , error) as your arguments in the error handler
try ```py
@client.command()
@commands.is_owner()
async def ownertest(ctx):
await ctx.send("jdbdb")
or just your id
You can do @commands.is_owner() to check.
@boreal ravine can I dm you
sure ig
i used !setxp 1 @The Flownery#9467
i want to get all
ctx.message
xD
you can use ctx.message.content to get the message that was sent....
i want to get the message that belong to message.author sent to used this bot, not the previous command from all in that channel
so , ctx.message.content is what you need
i aint really sure but seems like your bot client was unable to connect to the wavelink server
but why
oh ok i miss
i used await ctx.message.delete() before that command so..
send ur whole code
you can send the error first , and then delete the message
i don't know about node but i will try to help u
.
.
so you guys couldnt help me with youtube shit for my bot
could yall help me with spotify or is that bad too
we can help with that
alright, what do i import?
I think
is it spotipy?
from discord import Spotify ig
you cant play with spotify
and its also against their tos
son of a bitch
copyright laws dont just apply to youtube
I thought he meant https://discordpy.readthedocs.io/en/stable/api.html#discord.Spotify lmfao
literally anywhere on the internet
@client.command()
async def purge(ctx):
await ctx.purge(limit=1)
await ctx.send(f'Deleted {} message(s)')```
how do I make this so that the user can go $purge 5
and it will delete 5 messages
give the command an argument
add an amount argument
and pass it in purge
how to do?
what
in the arguments
you dont know how to add an argument to a function?
mhm
then what
pass the arg in limit
where can i install AVConv
so if I did $command "hello" 5
ig
purge 10
then py async def function(ctx, string, number):
no
amount:int
help meeeeeeeeeee
do you know what arguments, strings and ints are?
I am not sure how it understands the user message
It understands it using the arguments
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3.10/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3.10/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
its a builtin
@client.command()
async def purge(ctx, amount:int=1):
await ctx.purge(amount)
await ctx.send(f'Deleted {amount} message(s)')```
r danny is way easier than this omg
did I do line 2 correctly?
yes but line 3 is incorrect
purge is a method of TextChannel
- AttributeError
- You didn't specify the limit it doesn't know what
amountis if you don't putlimit=thenamount
Command raised an exception: AttributeError: 'Context' object has no attribute 'purge' lol
