#discord-bots
1 messages Β· Page 535 of 1
what?
then?..
because a command works?
a window?
i wont be too shocked if they say the command prompt
because the program stopped?
I guess but usually it would just say that it exited and wait for keypress
maybe that's just me tho
it isnt
rust is cooler
It is but Bash is still the 1st for me
Wish if coding bots was possible in bash
whats bash?
dies
the cool hacking stuff?
Yeah
rly?
Yes sir
revived
xD
π
Lmao good joke tho it wasn't a joke
ikr
why my bot does nt work
i have prefix "! "
Just saying
why my bot does nt work
doens't give any information for us to help
And we won't help you anyways
!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)
and this is Music bot when i want to play somwthing
oh okay
did he delete his code?
we can help you as long as it doesnt use YTDL
Yes
??? 
It did
then no helpy bro
key = None
# assign key (ctx,*,message)
global key
key = message
#use key
#do something and set key = None
i want to do something like this but it error what i should type in use and set key to None?
What are you even trying to do
This is like really weird to understand and seems messy
Can you make that number start from zero again at 12 every night?
what are u tryna do?
assign key and reset key
async def get_role(guild: discord.Guild, role: str):
role_obj = await discord.utils.get(guild.roles, name=role)
return role_obj
object Role cannot be used in await expression? line 2 btw
GUYS WHAT IS Key for?
How to make a antilinks?
Check if 'http' or any known domain is in the message.content.
!d discord.utils.get is not async iirc.
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
thanks :D
Yeah it's not a coroutine
when i run my code locally, its working fine, but when i deploy it on heroku it throws a file not found error
can someone help me with this
i want to know why its throwing an error
and what's in your Procfile
Shouldn't be working but worker
this is my file structure, im trying to read a png file using fr"icon/{name}"
^
i don't this thats the issue since all other stuff is working fine
its just having an error with files
it's worker
not
working
Not chaning that won't make your bot work better in any way either
So change it please
If you don't even listen to what we say why would we help you further
And yes it might be the issue because working might be used for something else and the files structure for that is maybe not the same
And that's all I'll say because you seem to be subborn and have a big ego, and I don't want to waste further time with that
i just asked the doubt, yu were being stubborn in the first place...
And since it's a reminder bot, you know that heroku clears all your files at midnight and get everything again from your repository right?
im trying to check if the bot can ping all the guild members but it only pings itself while theirs 2 more users the code:
for member in ctx.guild.members:
await ctx.send("member"f"{member.mention}")
Enable members intent
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
oh, i didn't know that, thanks.. but the file error still isn't solved, and im curious as to why its throwing that error
it worked thank you
Well does we can summon friend to our voice chat on guilds?
Does anyone know if there's currently a "best" library that implements slash commands, or one that seems to be pulling ahead in terms of quality? Last I looked there were several, and I know that the maintainer of discord.py is opposed to implementing them in his library and his library was previously the standard
You can't force someone to join a voice chat
Okay thanks
discord-py-interactions
I use edpy , but i can't recommend any forks yet
There isn't really a best right now, grounds are still shaky on that.
they have implemented the slash commands
disnake
although you could probably look at stuff like dislash or disnake or Nextcord or Pycord, or the many others out there.
To be fair I would not use a fork and use another language xD
Forks are quite often a mehh option
time.sleep() is a blocking function , don't use it
use asyncio.sleep() instead
ember.fields[index]?
i try natives value and the error comes up
from datetime import datetime
if datetime.now().strftime("%H:%M")=="00:00":
num=0
im not sure but this should work
I feel like it might take a while for a standard fork to come up, in the meanwhile you can accomplish context menus and slash commands with a mix of raw API and discord.py
e. g manual registration using the API combined with on_interaction
also check the resources for basic python knowledge
@commands.command() async def pause(self,ctx): await ctx.voice_client.pause()
I saw it
why it cant work?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
pls dont copy code and expect it to work and this can work and to fix your code you just need to indent/re-indent things
!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)
do u know how to make this (smth like that for my bot)
get_role:
(role.id)```
how to add a role by command?
ok thanks
i will remenber that
is it possible to set image on the playing status of bots
afaik no
Nope
Hello! I will appriciate if someone could help me! I'm making an Add role system for my bot. Something like if you type !freerole1 it will give you specific role. Thanks!
@commands.command()
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount):
try:
task_embed = discord.Embed(title=f"{amount} messages have been cleared.",
color=discord.Colour.blue(),
timestamp=ctx.message.created_at)
await ctx.channel.purge(limit=int(amount))
msg = await ctx.send(embed=task_embed)
await asyncio.sleep(3)
await msg.delete()
except Exception():
given_type = type(amount)
error_embed = discord.Embed(title="Error. Amount should be an integer.",description=f"{amount} is a {given_type}. ",color=discord.Colour.red(),timestamp=ctx.message.created_at)
await ctx.send(embed=error_embed)
Ok so im making a clear command and i want to send at the embed how many messages actually got deleted. Like if the input is 500 but there are only 10 messages in a channel then i dont want it to send "500 messages got cleared" i want it to send 10. Do i make a for loop for that or what?
role = discord.utils.get(author.guild.roles, name="Your role name")
user = ctx.author
await user.add_roles(role)
@jaunty folio help please
srry didnt want to ping you
dont work
line 5 error
purge method returns the list of messages deleted
So store it, and get it's length
Then you know how many messages got deleted
!d discord.TextChannel.purge returns a list of the messages that got deleted. You can use the len() function to get their amount.
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting botβs messages...
Ah. Already solved, my bad.
Pretty sure there's also an example on the documentation
So you can check it out there
uh show me error?
Thank you. Did not know that it actually returns that
ctx.guild.get_role(role_id).
Hm my solution works for me
Why did you define user?
Slows down
Pretty useless.
If you only use it once
And yes, slows down the process.
Yeah i know lol
Just remove it, redundant stuff
ok
role = ctx.guild.get_role(role_id)
await ctx.author.add_roles(role)
Or
await ctx.author.add_roles(ctx.guild.get_role(role_id))
xD
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Give code, error, etc.
Sorry but I don't quite understand, but using .join in a for loop is not really useful
idk what to do
this is my json content
I'd say loop trough them, and append the counter and current link to a string
ok den
Because doing a loop and using .join is probably not what you want to do
hm
You basically always overwrite
Because as you can see both URLs have \n\n{counter which is 2, so the last iteration}. in-between them
Can i create a Discord Bot that records audio from voice channels and send it to a particular channel?
like maybe a voice logging bot
What's the rate limit for rainbow role color? (ping me)
discord has said not to do rainbow roles
they overload the api
π’
But it's cool
It may be cool but it's bad
Β―\_(γ)_/Β―
Kraots answer Gurudatta's question, I wanna know the answer π
.
You can't as of right now
FUCK
But from what I've heard bots will get voice receiving in the future
sad
Idk when exactly since it's not really a topic that interests me
i thought i could make it w/ pypiwin32.
Nope, you can only do that on a user account

Bots don't yet have the voice receive endpoint
sad
@<>discord plz add zaat zing ok?
Anyone free to hop into a chat with me and help me out? Just started to dip my toe into the water of Python and am following freeCodeCamp's basic tutorial, but im hitting a snag
lets say i want to test if someone has reacted to the bots message with a specific emoji and if they have then it deletes it, how would i do that?
there is a specific function called on_reaction_add(reaction, user) but I think its for the bot
like the bot puts the reaction and user reacts to it
no problem
haha even I am watching a crash course on python
what do i have to import before it will work?
it says undefined name "reaction"
did you give reaction as a parameter?
?
oh yeah i forgot, im testing it on an existing command so i forgot to do that
no probs haha, it should work now
oh
code:
@Bot.command()
async def test(ctx, reaction, user):
await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
await ctx.add_reaction(":EBright:")
if reaction.emoji == ":EBright:":
await ctx.edit("lol")
error:
Ignoring exception in command test:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: reaction is a required argument that is missing.
right my bad I forgot to mention something
so
for on_reaction_add to work
the bot itself will need to add reactions to a message
and then when the user reacts, then something will happen
I have tried to do with user simply adding the reaction for which a task is assigned to a bot
but it gave error
like im just trying to get this to work, but they changed the command to tell the script what the OS key is so i followed that and i get just None in the output
Like... am i reading something wrong?
first wheres the token
"await ctx.add_reaction" is in there
lmao
thats what 'hal' is
hey I got it
ok so you have simply done ctx.add_reaction
you need to tell where
so...
maybe paste the token here and it will work
so you will need a statement like
message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
await message.add_reaction(":EBright:")
@fallow mauve
yo
Halloween is coming!!
im editing it
thats what the client is
just put client.run
what does that have to do with #discord-bots
oh wait wrong channel
lol
wait wrong server
alright
lmao
Im using Replit and they changed how that command works
yet when i do that, thats when i get the None message
replace it with client.run(os.getenv("hal"))
did you make it a variable in the secrets tab?
thats what gave me the big red spit out of dooooom
and yes its in the secrets as a variable
eeeyup
Im pretty dang sure i do
are all letters in the variable capitalized correctly
well it would give key error or something if it didnt
copied straight from the discord website
ahh
Like unless im being a total boob head and have done a total blodie
you have the key and value switched
OOOOOOOOOOOOOOOOOOOOOOOOOH MYYYYYYYYYYYYYYYYY GOOOOOOOOOOOOOOOOOOOOOOOOOD
lol
you got it xD
Holy shit look at that, it works now!
@fallow mauve did your command work?
no
good job haha
error:
Ignoring exception in command test:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: reaction is a required argument that is missing.
code:
@Bot.command()
async def test(ctx, reaction, user):
message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
await message.add_reaction(":EBright:")
if reaction.emoji == ":EBright:":
await ctx.edit("lol")
ok I think the problem is that
if reaction.emoji == "something" must be in on_reaction_add
and not in the command itself
so your command will have just one parameter ctx
and the on_reaction_add will have reaction and user
as parameter
@slow cove you shouldn't really be using repl. It's a bad idea
ive never used reactions for any of my bots yet so i have no idea how this works lol
This is literally my first dip into the python pool, I used to use a teeeeny bit of java like 13 years ago, so got any recommends?
Are you entering in reaction in the message?
?
@Bot.event()
async def on_reaction_add(reaction, user):
if reaction.emoji == ":EBright:":
await reaction.message.delete(user) # not sure if its purge or delete :/
@Bot.command()
async def test(ctx, reaction, user):
message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
await message.add_reaction(":EBright:")
this is something like it
Whats the message are you using to trigger the command
Run it on your pc
I am not entirely sure about it but the flow will be something like this
I do that haha
run it locally
as in CMD?
yeah
Yes
you could use powershell too. more or less the same as cmd
Reaction and user are required arguments. You're not entering them in
well thats a whole kettle of fish ive got not idea how to do, like where would i store the key? would that be a file i make in notepad or sumtin?
now you guys got me doing the hacker stuff
you could store it in notepad yes
But you will have to use open(file, mode) to read from that file and put it in the main program
Umm just use windows terminal its way more better than ps or cmd and idk why it isnt preinstalled on win 10
i gtg eat lunch, b back in a few
or you could just setup an environment variable file and then import dotenv
from there you can use load_dotenv to load that file and then os.getenv to get that variable
you can store the token in a txt, and make a function in a separate file that would grab the contents of the txt file and return it, and then store that in a TOKEN variable and then do client.run(TOKEN)
I am so lost, so for now, just to learn the basics i think ill stick to Replit, but ill defs look into that as a solution down the track
At least that's what I used to do if I knew someone was going to see the code, or else i just put the token on the code
When it comes to actually hosting the bot though, is it possible to host it locally and have it run off my machine instead of paying for a hosting site?
What is that lol
Do forgive me ive literally had less than an hour experience at this π π π π
itβd be interrupted if your machine turned off, went to sleep, or changed networks
if you do put token in the code directly
dont put it online accidentally
I once did the same thing
I had the token in the main program itself and then I uploaded file to github haha
Sure, just that if you want to host it 24/7 you need internet and your computer running 24/7 too
U domt know about windows terminal (btw its official) its basically like a linux terminal but for windows
I think we've all done that lol
I will check it out
Any links?
xD
you could host it on a raspberry pi
That's a better option
the microsoft store lol, iirc its preinstalled on win 11
thatβs what iβm doing (hosting on a pi)
Ive got a couple of old workstation computers that I was planning to use when i get a home server set up
haha I was planning to setup a google cloud server for my bot
don't know much tho, its simply an idea
Mine im making because a friend of mine made me one, was a ass hole to me, we had a fight, so out of spite she removed it. when my admins on my server use it QUITE FREQUENTLY
also it reminds me
arduino? for hosting? possible?
would be cool for testing haha
so now out of spite im teaching MYSELF python >:C
oh mann
that's one hell of a reason
dw you will get it eventually
It seems pretty simple compared to other languages ive seen
and a lot of my mates that use it praise it's versatility
python is easier compared to other langs haha
so the bot im trying to make is one that generates a random single use invite code for my server which I can then provide to peeps joining it to prevent code spreading
that's a nice idea
I wouldn't know though
I haven't explored that part of discord.py yet
how does one explore discord.py ?
the documentation
stackoverflow
connect things, make shit haha
where do i find that π π
google it
Okay β€οΈ
Idk how to work with JSON yet π kinda clueless
glad to be of help haha
You can overwrite the welcome value, either to None, "", 0
it will cause error in the event that fetches it
reading the source code ofc
whats the best way to turn a .py file to a .exe
#python-discussion and if they can't help #βο½how-to-get-help
yeah i did went there but nobody helped me
Then get a help channel
kk
How to make a slash command for a discord bot with a cog system?
How do I prevent the cooldown from triggering if the command encountered an error?
Create a bool
in you cooldown check for that bool
if ur command encountered and error then set the bool to False, simple!
reset the cooldown if an error is encountered
!d discord.ext.commands.Command.reset_cooldown
reset_cooldown(ctx)```
Resets the cooldown on this command.
I see, thanks
What is the mistake, please tell me
What are you doing with that json?
another slash command with the name "slash" already exists
Γ±
oh wait nvm
?
its the self.slash = β¦ line thatβs causing the error, you probably dont need it so remove it
saving channel ids
Why did I create a command, add a bot to the server, but there is still no command?
I guess you convert the json to a dict so maybe you can use dict.pop()
well i figured it out
had to pop the key
welcome
a weird doubt, can u change the name of the bot role to a new one from dev portal?
yes
or wait
u mean one that is created when the bot joins the server?
if so, nope
Anyone has experience with python and replit i built a webscraping script and i used selenium and chromium for it, it worked past few days but today it suddenly stopped working, it endless loads the page and it says request timed out
Yeah
I renamed my bot, so I wish to change the existing role name of bot
how to create a command to check if a member has a certain role type 'if member.role == 'staff': ctx.send('Congratulations you are a staff')
else:
ctx.send('You are not a staff. Press F for more respect')
you have to rejoin your bot
Then only it updates?
yes
get the role you want from Guild.get_role by passing in the id and and then you can check if role_that_you_got in Member.roles
Anyone tell me about encode ?
ctx.channel.purge(limit=x) where x is some number
That would delete any message, not the command message.
why
Anyone can help me with python bot.
.
?
yes
Where can i paste my error?
here
ok
Ignoring exception in on_message Traceback (most recent call last): File \"/usr/local/lib/python3.9/site-packages/discord/client.py\", line 343, in _run_event await coro(*args, **kwargs) File \"/home/user_437283638976053249/main.py\", line 126, in on_message users = json.load(f) File \"/usr/local/lib/python3.9/json/__init__.py\", line 293, in load return loads(fp.read(), File \"/usr/local/lib/python3.9/json/__init__.py\", line 346, in loads return _default_decoder.decode(s) File \"/usr/local/lib/python3.9/json/decoder.py\", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File \"/usr/local/lib/python3.9/json/decoder.py\", line 355, in raw_decode raise JSONDecodeError(\"Expecting value\", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
you need a {} in your json
I'd like to start programming but I don't like that they use if instead of whenever
so I'm not gonna do that
Bruh, i have a {} in my json
Thank you i tottaly forgot π
I can't create a permission check for the command could they help me?
you can use @commands.has_role()
as a decorator
or use role = guild.get_role(id) first and then paste it in if role in mu.author.roles
I've used it this way before, but I want to refine the error when a member doesn't have the role.
Ok
Thank you friend, it worked perfectly
div = soup.find("li", {"id": "randomword_1"}).get_text() div = div.strip() z = len(div) a = [ s[0] for s in div.split() ] x = 0 await ctx.send(f"{z} letters, first letter - **{a}** Ans.: {div}") while x < 3: def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel msg = await client.wait_for("message", check=check) intt = int(msg.content) if intt == div: await ctx.send("You won!") break elif intt != div: x += 1 await ctx.send("Try again!")
error: Command raised an exception: ValueError: invalid literal for int() with base 10:
maybe you guys know the solution
why are you trying to cast the string msg.content into an int?
Can he use @commands.has_permissions ?
@client.command(aliases=['ctc'])
async def createtextchannel(ctx, channelName):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='`{}` has been successfully created.'.format(channelName),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=embed, delete_after=5)
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
How can I create a voice channel from this command? What do I need to change?
Idk
I want to host my discord bot online but all the services are paid , does anyone here knows about any free services where I can host my bot for free??
I tried replit but it shuts down after 1 hr
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return 'Hello. I am alive!!'
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start() I'm using this on replit to keep my bot alive but it is also not working
Heroku > replit
DisCloud
tried this too but It also require paid membership after some time
Discloud bruh
Just use another account if that's the issue
oh okah , I'll try it
Just create 2 accounts and whenever one runs out of dynos switch to the other
That's what I'm doing
Thank you π
Β―\_(γ)_/Β―
also heroku psql is cool , at least it's free
hm but on the long run it is not practical
Β―\_(γ)_/Β―
you need a vps for long run
and there are some cheap vps out there
^
Like the host that @unkempt canyon is hosted on
Iirc it's hosted on linode
Ovh is yet another good and extremely cheap host
Β―\_(γ)_/Β―
wouldn't check for roles then
but if he has built up a good logic, then yes
i have this error idk why
online!
Traceback (most recent call last):
File \"/home/user_437283638976053249/main.py\", line 520, in \u003cmodule\u003e
@slash.slash(description=\"Mostra a latΓͺncia de qualquer membro\")
NameError: name 'slash' is not defined```
you have to use discord_slash
I use discord_slash
I use from discord_slash import SlashCommand
or name =none
Someone?
can help there?
??
@slash.slash(name = "" , description="Mostra a latΓͺncia de qualquer membro")
like this
@queen heart
@clear rapids do you know how to make this code work as voice channel?
@client.command(aliases=['ctc'])
async def createtextchannel(ctx, channelName):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='`{}` has been successfully created.'.format(channelName),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
await guild.create_text_channel(name='{}'.format(channelName))
await ctx.send(embed=embed, delete_after=5)
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
npπ
hm wait a sec
k
Are there any things I should do with my bot if i want to host it online rather than adding commands like
@client.command()
async def foo(ctx):
print('Hello')
hosting your bot has nothing to do with adding commands
I've seen many python open source discord bots that and rarely they do simple stuff like commands and those things, they have these huge files where they connect and do bunch of things, is there something im missing that a public discord bot has to have?
have you tried guild.create_voice_channel
https://github.com/thomas-xin/Miza
I mean, check this bot it has a lot of things, the bot has its own class and extends from discord.Client, what's the need and should I do it or should i just follow what the docs say?
Like this?
@client.command(aliases=['cv'])
async def createvoice(ctx, channelName):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='`{}` has been successfully created.'.format(channelName),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
await guild.create_voice_channel(name='{}'.format(channelName))
await ctx.send(embed=embed, delete_after=5)
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
channel*
you can customize some behavior and functionality of your bot by sub-classing discord.Client or discord.ext.commands.Bot
guild = ctx.guild
nothing with that? @clear rapids
!d discord.Guild.create_voice_channel
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
async def cv(guild , channel_name , category_name = 'VOICECHANNEL',user_limit = 10):
that's too much to do
and then await guild.create_text_channel(challen_name , category = category)
you don't need the guild parameter
wait leme write full code
ok
as you can access it by Context.guild
Are you typing it?
@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='{} has been successfully created.'.format(channelName),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
category = get_category_by_name(guild , 'any category name in the channel')
await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
channel = get_channel_by_name = (guild , channel_name)
await ctx.send(embed=embed, delete_after=5)
return channel
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
try this @shut axle
Okay
you can remove that guild parameter
I have edited it , I forgot to add voice
Where do I place ous=True? dexcom = Dexcom("username", "password") # add ous=True if needed
ous?
sorry!
sorry , not familiar with that api
never heard about that tbh
No, problem. Thank you anyways!
thats a very niche thing
does it work?
did you fix where I mistyped get as het?
but I think it is related to
category = get_category_by_name(guild , 'any category name in the channel')
channel = get_channel_by_name = (guild , channel_name)
the get_category_by_name and get_channel_by_name
@clear rapids
wht?
no category is different
and channel name is the name of that voice channel
But it is not working...
??
hm nothin , I was just doing it roughly before
hm send me the code that you are using now
@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='{} has been successfully created.'.format(channel_name),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
category = get_category_by_name(guild , 'VOICECHANNELS')
await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
channel = get_channel_by_name = (guild , channel_name)
await ctx.send(embed=embed, delete_after=5)
return channel
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
here it is @clear rapids
HUh
wait a minutes
NEVERMIND
it doesn't work /
wait a sec , did you changed the category_name??
to your bot test server's categories ?
yes
oh okah
@bot.command()
async def unban(ctx, members: commands.Greedy[discord.Member]):
for member in members:
await member.unban()
await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```
why does this not unban?
@clear rapids Any way to fix?
wait a min i'm trying
intents.members = True
add this
typehint as discord.User and use guild.unban
somewhere
although be careful, the user converter can call the API
where?
i dont understand xd
before the for?
yes
np, try and tell me if it works
okk
member would be in a guild
how do you wanna unban somebody from a guild
by getting him from the guild
oh true
that you wanna unban him from
@client.command(aliases=['ub'])
@commands.has_permissions(ban_members=True)
async def unban(ctx,user:discord.User):
guild=ctx.guild
mbed=discord.Embed(title='Success!',description=f"{user} has been successfully unbanned!")
await ctx.send(embed=mbed)
await guild.unban(user=user)```
this is what i use
and on top the intents.members=True
but mine is with more than 1 id
so how it would be?
i told you
if u donβt know what typehinting is and youβre literally doing it, you need to revisit your code or whatever
okkk
wtf
please leave?
yes
@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, members: commands.Greedy[discord.Member]):
for member in members:
await guild.unban()
await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```@hasty iron
discord.User
why? please dont discuss about this here.
not discord.Member
in async
yes
@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, members: commands.Greedy[discord.User]):
for user in users:
await guild.unban()
await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```
exactly
but
change the name of the list in async
to users
since this makes no sense
@shut axle
users: commands
?
def get_channel_by_name(guild , channel_name):
channel = None
for cnl in guild.channels:
if cnl.name == channel_name.lower():
channel = cnl
break
return channel
def get_category_by_name(guild , category_name):
channel = None
for cat in guild.categories:
if cat.name == category_name:
category = cat
break
return category
I forgot to tell you the def function
π
Can you type it in a command?
wht?
Where to put it on here?
@clear rapids
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'guild' is not defined @slate swan
okk
put it anywhere in your program , it is a function , you can call it anywhere
use discord.utils.find
!d discord.utils.find
discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is βMightyβ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unban() missing 1 required positional argument: 'user' now
@slate swan
bru
i put user in the ctx.guild.unban(user)
should work then
okk i try
I mean how to send it in a box?
@clear rapids The channel is taken from the first func
send what
embed*?
```` py
` ```
oh okah
like this without spaces
def get_channel_by_name(guild , channel_name):
channel = None
for cnl in guild.channels:
if cnl.name == channel_name.lower():
channel = cnl
break
return channel
def get_category_by_name(guild , category_name):
category = None
for cat in guild.categories:
if cat.name == category_name:
category = cat
break
return category
@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='{} has been successfully created.'.format(channel_name),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
category = get_category_by_name(guild , 'Voice Channels')
await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
channel = get_channel_by_name(guild , channel_name)
await ctx.send(embed=embed, delete_after=5)
return channel
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
oh , thnx
pep8 is crying
@shut axle do it like this
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10026): Unknown Ban @slate swan
why not discord.utils.get?
what the
On the second func you need to change the channel = None
because it has taken
code is this py @bot.command() @commands.has_permissions(ban_members=True) async def unban(ctx, users: commands.Greedy[discord.User]): for user in users: await ctx.guild.unban(user) await ctx.channel.send(f"He desbaneado a: {user.mention} del servidor!")
channel = discord.utils.get(guild.channels, name="channel-name")
maybe the user you got is not banned?
discord said they arenβt
oh my bad
now check if it works?
I wonder what the next random shitpost is gonna be
also channel = get_channel_by_name = (guild , channel_name)
remove the = after by_name
!d discord.on_guild_role_create
discord.on_guild_role_create(role)``````py
discord.on_guild_role_delete(role)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") creates or deletes a new [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
To get the guild it belongs to, use [`Role.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role.guild "discord.Role.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
oh okah
!d discord.on_bulk_message_delete
then you couldβve modmailed
Hey guys
wat
Could a command ignore arguments after alias?
i write good python code
example: /hi Anthony
would normally execute async def hi(ctx):
You could've opened your PR after you fixed your type errors
so what exactly you want to do
ughm i wanted to create a command /ball . typical 8-ball command but it should ignore arguments
No I haven't reviewed it yet blanket
just replying with some message
but can you review cooldowns I commited las tnight
i ve done that already but i shouldve used (ctx, *, question) and it worked could i not use so much arguments that i dont actually use in def
iirc, you don't need to have anything but ctx
discord.py will just ignore the extra words after the command, and the argument
oh like that ".'"?
nah i mean just ignore everythin after /ball
cuz last time i tried it it gives error
im not sure actually but
if this is true then im just stoopid
im new at python and bruh
okah , and whats your prefix?
Let me guess, literal eval?
if you don't declare extra parameters other than ctx, it won't parse the extra arguments and ignore them
command_prefix="/"
i just clicked a β¦ on my review and clicked share
Sends me to my comments
its in get_context
but why the hell will you add a command that you want to ignore if it is used????
just delete it
ignore the extra arguments not the command itself
i mean ignore words after the command
What's wrong with it
/ball Will Shawn eat rice in 20 minutes
oh I get it
SO it just runs async def ball(ctx)
you dont see this or whatever
No I missed that comment
bruh
I will change that yes
and also get_prefix still doesnβt check if its a coroutine function or not
you want it to run even if someone write something after /bal?
the prefix that was passed in
@clear rapids@clear rapids look
hm gime a min
okah
Just don't have any arguments apart from ctx
discord.py will ignore everything else by default
def get_channel_by_name(guild , channel_name):
channel = None
for cnl in guild.channels:
if cnl.name == channel_name.lower():
channel = cnl
break
return channel
def get_category_by_name(guild , category_name):
category = None
for cat in guild.categories:
if cat.name == category_name:
category = cat
break
return category
@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'Voice Channels' , user_limit = 10):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='{} has been successfully created.'.format(channel_name),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
category = get_category_by_name(guild , 'Voice Channels')
await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
channel = get_channel_by_name(guild , channel_name)
await ctx.send(embed=embed, delete_after=5)
return channel
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)
When I do: ?cv Voice Channels hello
it is create a voice channel called : Voice ...
@clear rapids %^^^^
it actually created a vc?
oh
thatβs way better now
i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".
Right I need to add that
I dont have permission to speak
Perhaps a maybe_coro function?
@shut axle
sure
It takes the args as channel_name=Voice, guild=Channels, category_name=hello
hm okah
also commands should be able to make multiple checks
which vc?
anyone know how to slove it
then in the handler it runs all
@shut axle
Private
but you dont check in Command.__init__ for callback.checks
I do
On DM's
what
huh
I literally have a hasattr right there
thats for check
lefi/exts/commands/core/command.py lines 21 to 23
if hasattr(self.callback, "check"):
self.checks.append(self.callback.check) # type: ignore```
hm just join #code-help-voice-text
i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".
You just decorate it multiple times
The deco returns the func, so you can keep adding on
code/help 0
Although init runs once so I can just fix by making the deco append etc
or do command lookup via name
Can prob do some hacky stuff with __call__
but it will override the last check
Yea, I realized

append as in making it a list
thatβs what i was saying
that's what i was saying
I don't think I'm merging now
Since I don't even have "cogs"
Were calling them plugins, :^)
guys pls
yoink novaβs idea
help
π―
just ask, dont ask to ask
i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".
code?
@bot.command()
async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
if member == None:
return
if ctx.guild == None:
return
result = await self.find_or_insert_user(member)
user_id, guild_id, xp, level = result
print(xp, level)
level = lvl
cursor = await self.db.cursor()
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
await self.db.commit()
await ctx.send(f"{member.mention} level changed to {lvl}")
cuz i need it so this can work:
result = await self.find_or_insert_user(member)
**** cursor = await self.db.cursor()
this is a cog?
no
what?
do i need to make class?
it wonβt work regardless
you seem to be confused on where self is used
do you actually know when we should add the self argument to a function?
This is empty by default
@commands.Cog.listener()
async def on_member_join(self, member):
welcome_events = db.find_one({"guild_id": member.guild.id})["welcome-events"]
chan = db.find_one({"guild_id": member.guild.id})["welcome_channel"]
channel = self.bot.get_channel(chan)
message = db.find_one({"guild_id": member.guild.id})["welcome_message"]
title = db.find_one({"guild_id": member.guild.id})["welcome_title"]
footer = db.find_one({"guild_id": member.guild.id})["welcome_message"]
embed = discord.Embed(title="",description="",color=discord.Colour.from_rgb(255, 255, 255))
if welcome_events is False:
return
if channel is None:
return
if message is None:
embed.description += f"Welcome to {member.guild}!"
if title is None:
embed.title += ""
if footer is None:
embed.footer += ""
else:
embed.description += message
embed.title += title
embed.footer += footer
await channel.send(embed=embed)
should i just do embed.footer == None?
dont feel like that would work
if footer is None:
pass
like this?
that makes sense lol idk why i didnt think of it
No your thinking about this the wrong way,
You check if footer is not None, this is good
And if its none, that's where you run embed.set_footer
Otherwise if the footer is None it will not run set_footer and the embed will not have a footer
@client.command()
async def pickwinner(ctx):
channel = client.get_channel(764581973044756501)
msg = await channel.fetch_message(898309597104857128)
``` How could I make this command choose a random reaction from the defined message so they will win the giveaway?
else:
embed.description += f"{message}"
embed.title += f"{title}"
embed.footer += f"{footer}"
``` so do i need this
just forgot elif
No shit sherlock, it was meant to insinuate his questioning.
@commands.Cog.listener()
async def on_member_update(self, ctx, member_before, member_after):
nickname_after = f"{member_after.nickname}" if not member_after.nickname else member_after.nickname
nickname_before = f"{member_before.nickname}" if not member_before.nickname else member_before.nickname
embed = discord.Embed(timestamp = ctx.message.created_at , color = discord.Colour.random() ,
title = "Member Update")
embed.add_field(name = "Nickname before:" , value = f"{nickname_before}" , inline = True)
embed.add_field(name = "Nickname after:" , value = f"{nickname_after}" , inline = True)
embed.set_thumbnail(url = f"{member_after.avatar.url}")
embed.set_author(name = f"{self.osamu.user}" , icon_url = f"{self.osamu.avatar.url}")
channel = self.osamu.get_channel(898199584726188042)
return await channel.send(embed = embed)
So I've tried to make an event which allows me to log whenever someone's changing their nickname. However, the following error occures:
Ignoring exception in on_member_update
Traceback (most recent call last):
File "/home/ohnezahn/.local/lib/python3.9/site-packages/discord/client.py", line 352, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_update() missing 1 required positional argument: 'member_after'
welcome_events = db.find_one({"guild_id": member.guild.id})["welcome-events"]
chan = db.find_one({"guild_id": member.guild.id})["welcome_channel"]
channel = self.bot.get_channel(chan)
message = db.find_one({"guild_id": member.guild.id})["welcome_message"]
title = db.find_one({"guild_id": member.guild.id})["welcome_title"]
footer = db.find_one({"guild_id": member.guild.id})["welcome_message"]
embed = discord.Embed(title="",description="",color=discord.Colour.from_rgb(255, 255, 255))
embed.set_author(name=f"{member.guild.name} | {member.guild.member_count} members",icon_url=member.avatar_url)
if welcome_events is False:
return
elif channel is None:
return
elif message is None:
embed.description += f"Welcome to {member.guild}!"
elif title is not None:
pass
elif footer is not None:
pass
else:
embed.description += message
embed.title += title
``` it wont add the description
How to sandbox a cog?
@client.command()
async def pickwinner(ctx):
channel = client.get_channel(764581973044756501)
msg = await channel.fetch_message(898309597104857128)
a = random.choice(msg.reactions)
await ctx.channel.send(f'{a}')``` I think I'm close, currently it just sends the reaction how can I make it so it sends the random user's name?
i need help w something, im trying to learn how to make an economy bot and its not working:
error:```
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
code:```py
import discord
from discord.ext import commands
class WorkCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def test(self, ctx):
await ctx.reply('Testing!')
def setup(bot):
bot.add_cog(WorkCommand(bot))
import discord
from discord.ext import commands
from pymongo import MongoClient
cluster = MongoClient("")
db = cluster["Feature"]["user_data"]
class EconomyCMDS(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def bal(self, ctx, member:discord.Member=None):
member = ctx.author if not member else member
if member not in db.find_one({"user_id": member.id}):
db.insert_one({
"user_id": member.id,
"bal": 0,
"bank": 0,
"inventory": [
],
})
await ctx.reply("You have a balance of 0. Because you have just started using these commands")
else:
bal = db.find_one({"user_id": member.id})["bal"]
bank = db.find_one({"user_id": member.id})["bank"]
embed = discord.Embed(title="feature",description=f"`Balance:` **{bal}**\n`Bank:` **{bank}**")
await ctx.reply(embed=embed)
def setup(bot):
bot.add_cog(EconomyCMDS(bot))```
code ^^^
```py
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.econ' could not be loaded.
``` error ^^^
ExtensionNotFound
I know this but i cannot figure a way to fix it
Take the command out of the __init__ method
What's the name of your file
Folder?
thx, just an indent, how did i not see that
mhm
Can happen, also have this quite often in other languages xD
for filename in os.listdir('./commands'):
if filename.endswith('.py') and not filename.startswith('_'):
bot.load_extension(f'cogs.{filename[:-3]}')
logging.info(f"loaded cog: {filename}")
ita already looking thru the folder
yeah, its really easy to miss but it makes you feel stupid once you see it lmao
Agreed
maybe because it doesnt have the pycache folder?
No
Maybe set a name to the cog after the commands.Cog in the class definition
Because the code seems normal, at least I can't spot anything
Create a list and eventually save it in a database or a JSON file if it's not too big
Append to the list
Remove from the list
Use random.choice
That's basic Python knowledge
so frustrating
??
Like name="econ"
just put that under self.bot = ?
list = []
x = "l"
list.append(l) maybe
No, after the commands.Cog in the class parameters
ohh i get what your saying
Have you learned Python before doing bots?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I'd learn Python before directly starting with a bot
And I wouldn't stayed on discord.js
Because discord.py's development has been stopped
.
i need help, i am using cogs with discord.py, (note: this has been happening even since discord.py was abandonded) everytime i use the "help" built-in command it freaks out on me and sends so many help messages at once, been trying to fix it for a while but have zero idea whats going on
You should be using Motor not pymongo https://motor.readthedocs.io/
Pymongo is blocking, it'll stall your bot whenever it does anything which is obviously not ideal for a bot being used by multiple users at the same time
Motor is async and won't cause that problem.
try printing message and seeing what's in there. The code seems fine 2 me so it may be an issue with what's in the variable. Is there an error? Is the embed sending anything?
have you modified the help cmd at all (subclassed it?)
if not, are you 100% sure you aren't running multiple instances of the bot?
nope, 1000% sure
this has been on going for ever since i started
and its not only that, even if i remove the discord help and add my own named "help" it does the same
do you use process_commands anywhere
lemme check
yes , once
it can duplicate if you use it twice
idk then, can try asking in the d.py serv too https://discord.gg/dpy
Because of the default help command
It's broken somehow
No idea how this managed to happen
!d set
class set([iterable])``````py
class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.
Sets can be created by several means:
β’ Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`
β’ Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`
β’ Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
is embed.description == "h" valid??
i'm trying to set the description based on a variable not add something to it
oh i already fixed it LMAO
Just do discord.Embed(description=var)
this is so wrong in so many levels
do what water_gazes said
== is checking for equality so no
i see, iβve used TinyDB before but never got it to go anywhere since my client backed out last second π
Any database should be good
so as long as you use an async driver for it, as discord.py is an async environment
what made you come up with lefi?
So, I have a database setup. How could I make a mute command (with time) that persists over a restart?
I have no idea what I need to store, nor how I check if the time has extended the database time.
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.econ' could not be loaded.
what could be the causes of this
class EconomyCMDS(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def bal(self, ctx, member:discord.Member=None):
member = ctx.author if not member else member
if member not in db.find_one({"user_id": member.id}):
db.insert_one({
"user_id": member.id,
"bal": 0,
"bank": 0,
"inventory": [
],
})
await ctx.reply("You have a balance of 0. Because you have just started using these commands")
else:
bal = db.find_one({"user_id": member.id})["bal"]
bank = db.find_one({"user_id": member.id})["bank"]
embed = discord.Embed(title="feature",description=f"`Balance:` **{bal}**\n`Bank:` **{bank}**")
await ctx.reply(embed=embed)
def setup(bot):
bot.add_cog(EconomyCMDS(bot))
``` thats the code in files with some imports obv
anyone got an idea when i do for member in ctx.guild.members with intents all on it only returns 9 members instead of the 70 members?
why call yourself a Full Stack Developer
then lmao
The name or the wrapper itself?
wrapper
I've been seeing a lot of shitty forks recently and bad attempts
So I decided to do it myself if I can't let others
whats the issue im mad
fair enough
emojies wont work like they should
jesus christ
@client.command(aliases=["slots", "bet"])
@commands.cooldown(rate=1, per=3.0, type=commands.BucketType.user)
async def slot(ctx):
""" Roll the slot machine """
emojis = ":apple::tangerine::pear::lemon::watermelon::grapes::strawberry::cherries:"
a = random.choice(emojis)
b = random.choice(emojis)
c = random.choice(emojis)
slotmachine = f"[ {a} {b} {c} ]\n{ctx.author.name},"
if (a == b == c):
await ctx.send(f"{slotmachine} All matching, you won! :tada:")
elif (a == b) or (a == c) or (b == c):
await ctx.send(f"{slotmachine} 2 in a row, you won! :tada:")
else:
await ctx.send(f"{slotmachine} No match, you lost :cry:")
oh xD can u help
emojiList = ["emoji1", "emoji2"]
thx
obviously, replace the emoji1 and 2 with your own
with a listen event, how do i make it detect whether the message is exactly as stated
do you want just an exact message or a list of them?
one exact
#if u use cog
@commands.Cog.listener()
async def on_message(self, message:discord.Message):
if "string" in message.content:
return
#if u dont ig use this idk LMAO
@bot.event
async def on_message(message:discord.Message):
if "string" in message.content:
return
oops
k
something like that i guess?
ill try it
allright
i think i found an easier way actually
im gonna stick with that cuz i gotta go eat dinner soon and i dont have time to figure other ways out rn
one sec
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
thx
<@USER_ID>
or <@!USER_ID>
slotmachine = f"[ {a} {b} {c} ]\n{ctx.author.name},"
how would i do it im confused it doesnt work
why do i get this error Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 43, in on_ready
if not db.find_one({"guild_id": server.id}):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/collection.py", line 1328, in find_one
for result in cursor.limit(-1):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1238, in next
if len(self.__data) or self._refresh():
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1130, in _refresh
self.__session = self.__collection.database.client._ensure_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1935, in _ensure_session
return self.__start_session(True, causal_consistency=False)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1883, in __start_session
server_session = self._get_server_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1921, in _get_server_session
return self._topology.get_server_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 520, in get_server_session
session_timeout = self._check_session_support()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 504, in _check_session_support
self._select_servers_loop(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 218, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 6168c65e5605563b88d1ebcb, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('vora-db-shard-00-00.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('vora-db-shard-00-01.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('vora-db-shard-00-02.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>
jesus christ dude, summarize the error
fr
something with your database is messing up
anyways
help @slate swan pls
slotmachine = f"[ {a} {b} {c} ]\n <@USER_ID>,"
mmmmm, Implementing plugins is gonna be a pain
I gotta make a metaclass to wrap all methods
@slate swan , all you need to do now is to get the context author id and replace that with USER_ID
@slate swan
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'USER_ID' is not defined
xD
bruh
you have to get the users id
then replace the "user_id" with the users id
yeah, what he said


