#discord-bots
1 messages · Page 970 of 1
channel_id = int(channel_id[2:-1])
new = test[2:-1]
Just that?
it will remove the <# and >
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
``` Change that to?
yeah your current channel id has <# > around it for some reason
can't turn that into int
Yeah because the str
yes you need to remove those characters befor you can turn it to int
no, keep that and whereever you use channel id do the slice channel_id[2:-1] to get rid of characters that are not numbers
removes the first two and last character
But why did it work before?
allg thanks
idk im sorry
@commands.command(name="kick", description="Kicks a user from the server")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if member == None:
await ctx.send("Please mention a user")
else:
await ctx.guild.kick(user=member, reason=reason)
channel_id = self.log_channels.get(str(ctx.guild.id))[0]
channel = self.client.get_channel(int(channel_id))
embed = discord.Embed(title=f"{ctx.author.name} kicked: {member.name}", description=f"Reason: {reason}",color=0xff0000)
await channel.send(embed=embed)
await ctx.send(f'Kicked **{member.name}** for **{reason}**')
``` this worked like 10m ago so weirdd
Do you still have the error handler I showed once?
How to make channel rename command
thats indeed weird
Uh not the one that shows it discord, it was very annoying that it showed a error when I did like .a that it showed the error
!d disnake.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_channels "disnake.Permissions.manage_channels") permission to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
ty
@minor totem Any idea?
Well did you replace the sending with printing or something?
I can't have an async property right?
I'm pretty sure it'll error but any alternatives?
Do I have to write this?
await edit(*, reason=None, **options)```
no
idk how to use docs
await channel.edit(name='new_name')
ok ty
You can, but please don't.
how can I do that?
How can i delete message no purge?
Just like you'd expect to, define it with async def
but it errors though
What do I have to type in
(name = "")?
Just new_name?
oh wait I forgot the brackets () to the function my bad
if you want to rename your channel, you need to pass in that argument
just any string works
ok
so for ```py
@property
def something:
return somethingelse
you can do `something` without the ()
but if it were async you need the () right?
Nah it errors for both
how should I define channel?
the first doesn't error I'm pretty sure
get/fetch the channel object by an id
a property needs to be a normal method with a @property decorator
usually passed in by a user as a param
i mean you can have an async one, but what's the point
Why not try? If you're trying the async one..
by using this?
guild=discord.Object(id=)
yes sir
at that point you'd just use a async function yeah
Properties should not have side-effects
no
channel = guild.get_channel(id)
oh wait I'm confused i tried it but it said couroutine object isn't callable
typo
i have no idea what to draw on these cards 
i think the only thing that will fit is dots
what would the side effects be?
Would be even better if asynchronous setters actually worked
I'm not going to do it, I just want to know
Why would you have that though 😮💨
Do I have to type channel id or guild
yeah, to get/fetch the channel
But I want the bot to rename all the channels in the guild not 1
how do i make my bot send something when it gets pinged
yeah, just loop through all the channels and rename them
@bot.event
async def on_message(message: discord.Message):
if bot.user.mentioned_in(message):
print("I was mentioned.")
await bot.process_commands(message)```
Wdym loop through all the channels?
for channel in guild.channels:
await channel.edit(name='new-name')```
just use ctx.guild
Its not working
how do I get user from user id if I don't have client instance, but a bot instance (or only commands.command())?
I know this, but it demands client
user = await client.fetch_user(id)
what is the max .rar file size that a bot can send to dm ?
you forgot to define the async func, and indent
You never defined the function
8mb ig
nice
neat
Lol
So what should I do
To rename the channel where command has been written?
await ctx.channel.edit(name='new-name')
Do I have write this command to rename it?
await ctx.chanel.edit(format(message_content))
no
no
Without format?
@bot.command()
async def rename(ctx, new_name: str='new-name'):
await ctx.channel.edit(name=new_name)
Why cant it rename renamed channel?
what do you mean?
It can't rename already rename channel
So I renamed a channel
And used the same command but wanted to change the name
It didn't work
how to fix?
did you get an error?
No
Code
@quaint epoch
&?
Command "?" is not found
did you change the name? or did you maybe just renamed the channel to the same name again?
Ofc I changed the name
huh
Not essential but it’s a cool feature
add a check that excepts mentions from bots
Nvm I think I fixed it
noob bug
Share yr code
sorry
sorry didnt mean to offend you, would just have been something that could happen to me
perfect
is + 500 lines of code..
Send the line that made an error +10 -10
The bot is just slow
How can I increase the speed?
@client.command()
@has_permissions(manage_channels=True)
async def rename(ctx, new_name: str='new-name'):
await ctx.channel.edit(name=new_name)```
@sullen pewter will you help me?
is it just this command thats slow or every command?
Side effects means that something changed. Something that has no side effects, is idempotent and will always return the same thing.
For example, having a next_id implemented as a property would be very bad design because accessing it has a side effect - instead, you should have a next_id() method.
tbh i never used commands and never worked with methods to increase speed
Ic
?
I see
ah ok
Why is the command slow?
Can you help me @quaint epoch please
it's python
it can't be that fast
and also, there is a ratelimit like 5 requests a second/minute
so expect it to take some time
@quaint epoch can you help me??
w/ what
well these look pretty meh 
show the full traceback
looks like you're trying to send an empty message 
Got it. Also what's idempotent?
yes but i need to see the line where it occurred
have you checked the message isn't empty
@quaint epoch
okay, show the line where it occurred
Something that has no side effects. Accessing an attribute should be idempotent - you can do it a billion times and the result won't change (unless you change the attribute).
Deleting an attribute isn't idempotent for example, after deleting it once you can't delete it again.
6k?
Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
from the docs
@quaint epoch
the line of code
I have this error everywhere when it is embed
ah yeah
wait
which line exactly do you want to see?.
any line
you said it is occurring on any command where an embed is sent
embeded_response = discord.Embed()
embeded_response.title = "title"
embeded_response.set_image(url)
await channel.send(embed=embeded_response)
if i try to embed an image it gives me this error:
TypeError: set_image() takes 1 positional argument but 2 were given
any ideas?
the url is a string and works
bruh
huh?
@quaint epoch look this
!d disnake.Embed.set_image
set_image(url=..., *, file=...)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.Empty "disnake.Embed.Empty") removes the image.
it requires a positional argument
which means?
where are you getting title, footer, and icon from?
you need to do url=url
ohh ok thank you
does anyone know how to make a leave server command? ex: -leave (SERVER ID)
config.json
yeah i works now
print all the values before creating the embed, to check if they are valid
await guild.leave()
that is very broad
hmmm
i've never used select menus before
!d disnake.ui.View
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
class disnake.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Select.values "disnake.ui.Select.values").
New in version 2.0.

config.json
https://https://discord.com/developers/applications
i know, but print out the values before creating the embed to make sure they are valid
this is javascript
this is a python server
yes
pls edit@bot.command() async def help(ctx): em=discord.Embed(title=title, description=f"{prefix}suggest **(create suggestion)**\n{prefix}serverlogo **(send server icon)**\n{prefix}serverbanner **(send server baner)**\n{prefix}userinfo **(send userinfo)**\n{prefix}ipingo **(send ip information)**\n{prefix}embed **(send embed message)**\n{prefix}botinfo**(give info bot)**\n{prefix}ping **(ping bot)**\n{prefix}encode **code text)**\n{prefix}decode **(decode text)**\n{prefix}say **(bot send message on server)**\n{prefix}portfolio **(look my portfolio)**\n{prefix}admhelp (only admin command)```",
color=color)
em.set_footer(text=footer)
em.set_thumbnail(url=icon)
await ctx.send(embed=em)```
i can't spoonfeed
okey
run this code before defining embed print(title, footer, icon)
these playing cards look more interesting or just confusing
no
confusing
this message was for @slate swan
@slate swan , check out the discord.js server i sent you
navigate to bot, and reset your token
then paste the token in the .run

or just paste it here so that i can run their bot which will make their server better
👀
@quaint epoch good?
yeah
ashley can you take over for a bit while i complete my math tests
i have about 10 minutes left
okay, now show what the print statement outputted
What
show the line
@quaint epoch

no such
i'm tired of messing with these cards now
yes 0
that's your error, title, footer, and icon don't exist
how?
they are all either empty strings, or just don't exist
so your going to need to solve
why those are all empty strings
HRLO77 out
now this is confusing
are you running a python bot, or a js bot?
because you keep showing screenshots of both
@quaint epoch {"token": "", "prefix": "n?", "color": "#e70505", "title": "THANOS-GIGACHAD", "icon": "https://pbs.twimg.com/media/EmZIthXXEAICf_Q?format=jpg&name=large", "footer": "BY NEONITO#8189"}
🤔
!d disnake.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
This module provides access to the select() and poll() functions available in most operating systems, devpoll() available on Solaris and derivatives, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
Note
The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used.
a few days ago it worked and now it magically doesn't.....
try pasting the values directly, instead of reading from the .json
what do you mean?
somehow improve cfg to make it work with json as before
Hey, how can i create an command that ask you 3 questions: Channel id, Titel, Text and send with this Information an embed?
try that?
@quaint epoch haha
it doesn't work that way either....
@livid jacinth maybe you will be able to help somehow?
which ones 
What is it about?
look this
I have this error everywhere when it is embed
What's with the print
there aren't :(
that's not even python 
!d discord.Embed.url
The URL of the embed. This can be set during initialisation.
@slate swan ^^^
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
since when 😔
🤷
How do I make the cooldown less for a certain role?
have you experimented with the type kwarg?
You cannot set it to anything else
Nvm
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
interesting
Yea haha just saw
video embed
Well, worth a try. Prolly that is how discord shows embeds for vids and stuff
brb checking what that is
How to make on bot join command?I mean , when bot join in guild,a command executed
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
How do I make the cooldown less for a certain role?
huh?
I know I am wrong stop it
it is, it sets a hyperlink on title
idk i am now confused more
oh ic
I wasn't talking about the url kwarg, was talking bout the type kwarg
well
not string list
enable members and guild intents
already enabled
in your code too?
list*
and if it wasnt enabled it would threwn an intents error
ye
yes
show
disnake 😔
ye lol
How do I make the cooldown less for a certain role?
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")
??
same thing
the file doesnt have a setup function
even in discord.py i get same
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
command_prefix is required
its discord.Client
but why
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
what is in number 9 put in number 8
pls help any1 it's urgent
it's 'hi'.format(...) not ```py
"hi
".format(...)
did you enable the intents in the developer portal?
Yes
@proven ore did you disable chunking?
what's chunking
when you put “disnake.intents.All()” you need to have all the intents enabled in the DDP i believe
i do
this
i tried Intents(members=True, guilds=True) as well
presence intent, server members intent and also message content intent
all intents are enabled
Make a dynamic cooldown
so use f string and fuck .format 🗿 copy pasted tutorials sucks
how? I've never used that before
or you know you could calm down and actually explain what they are doing wrong in a nice and informative way
os.getenv("TOKEN") is None, which means the token isn't an environmental variable

which discord.py version are you using?
you didnt set a token in the ENV variables
remove “.format” and just put f’Logged in as…’
in replit there is an "enviroment variables" tab
I am calm, wdym
with the f right before the string
in code as well
any ideas for small games for bots i can code? like rock paper scissors or smth
seemed very provocative by openly saying “copy paste tutorials suck” when they seem to be new to coding and are following tutorials to start
minesweeper :troll:
anyone
whatr
you should know that before doing any projects you should have minimum knowledge of Python. And this is a fact, you don't just copy paste and then just come here and say why is not working when you also don't know what are you doing .
show a screenshot of where it gives empty list
print(f'Your text {client.user}')
for server in self.config['servers']:
guild = await self.fetch_guild(self.config['servers'][server])
print(guild.members)
that does the equivalent of .format just quicker and smaller
we all start somewhere with different ways and techniques, don’t flame someone for doing it in a way that YOU don’t appreciate
they asked a simple question
they expected a simple answer
and he had a simple answer. use f string.
stop being so butthurt
no, your whole line should be: print(f'We have logged in as {client.user}')
is there some way to web scrape a website into a bot?
do you even know the basics of Python?
chill
yes
you knwo that your bot token is there, yeah?
he clearly doesn't
in three line of console
this person quite obviously didn’t know what f string was, as the tutorial they were following was showing the basics without using f string and using .format instead
@proven ore can you try getting the guild from the bots cache, see if anything changes
One reason to not follow tutorials
client.run(os.environ['Token'])
Secret:
Name: Token
Value: (bot token)
Use a webscraping library (bs4 perhaps..)
@slate swan
we can't help people make a bot if they don't even know what's a f string. go ahead and spoonfeed him then he will always come here and expect other people will write code for him. It's not disrespectful to ask for them to have minimum knowledge.
Ares do be mad
so, create a file called “config.env” inside put “token=tokenhere”
then in your main.py, replace the token you put at the end (the one you censored) just type “token”
yeah like that, have not used replit but this seems correct
the fetch_guild is working tho, it is returning a Guild
it returned None
how can i make my bot send a chosen image from my pc ?
No
;-;
@proven ore can you print the guild object repr for me and show the output
Just write
client.run(os.environ['Token'])
And create a secret in replit commands
Name: Token
Value: (bot token)
Yess
where's the reprs 
hello
use the repr function
Hi mina
What is that?
nice name change, only realized haha
Are you streaming videos off youtube?
idk man, we dont help with ytdl here
Yes
there's a lot of them haha
Not surprised
Ah, unfortunately in accordance with rule 5, we won't be able to assist you with that :(
member_count = NOne hmm
<Guild id=869724417406697532 name='8BF' shard_id=0 chunked=False member_count=None>
damn, that’s a hell of a way to think, i disagree with you, tutorials exist to introduce someone to coding and understanding, this person did not know about the existence of fstring because once again the tutorial they followed didn’t use fstring because, hate to break it to you… not everyone uses fstring
“he will always come here and expect people to write code for him” except this is probably not going to happen, as they have literally just created a bot and are working to get it running, they came here for help on 2 errors, they expect help, don’t insult or get hotheaded at someone for asking a questing that might be really simple for you, but wow, it’s not easy for them
i won’t respond any longer, this should be enough and this argument is going nowhere
@boreal ravine
That happens when you don't have the right intents
member count = None
well all intents are on
You're using .all()?
yeah
looks like the guild is unavailable? 🤔
And is it turned on in the dashboard?
i tried using Intents(guild=True, members=True)
I remember seeing some discussion about member_count being None in a github issue
Yeah
Danny mentioned it wasn't important to set the typehint to be Optional since it's very rare
Stop,youtube_dl is illegal?
Not illegal, per se
!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)
Breaks ToS
I agree with you ngl
Judging anyone on the basis of their knowledge of some of the non beginner Python concepts (like f strings (like in this case) or ternary statements) isn't really a good way
sooo?
It's more or less a discord issue, i don't believe there's much you can do about it
hmm
if you want your bot to run put: client.run('yourtokenhere')
so nothing
this is not a good idea as your token is unprotected
No just write
client.run(os.environ['Token'])
Just write Token(not your token,just word Token)
!mute 398388882544132096 2d don't know how many times we need to have this conversation. if you don't shape up you'll be removed from the community for good.
:incoming_envelope: :ok_hand: applied mute to @hoary cargo until <t:1649870681:f> (1 day and 23 hours).
its only with python?
env vars
Doubtful
Yes
key:Token
key: Token
Value: (your bot token)
value:yourbottoken
value as the bot token
the súper long one
no
without brackets
Write your bot token
@slate swan I advise you to familiarize yourself with the basics of Python and replit functions
Yes
what is your client.run() at the end? what does it look like
how can i define a role, that only that role can access on that command
This is very important if u want programming
Looks like you have an on_message, make sure to process_commands
os.environ
ok. make it so that it’s: client.run(os.environ('Token'))
Not os.getenv
Oh, nevermind. Looks like you're also using client so I suppose it doesn't matter
anyone
it’s different on replit i believe
!d discord.ext.commands.has_role use this decorator and pass in the id/ name of role (id is recommended)
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
not that
i use getenv which is why i said getenv, but since replit has it built in it’s just environ
um?
(i’m guessing)
i want to spesify that return user only with a spesific role
You can simplify this
both getenv and environ can be used, but getenv is preferred since it returns None if the key isn't found which is safer than raising an error and stopping the whole bot (as long as u not talking bout the bot token)
Can you give me full code without token?
mind sending a screenshot of the whole file?
Indents?
wdym, like if the user has a specific role the command should be ran further else it should return a message about inelegibility
u forgot to close the quotes somewhere
He wants to prolly check the user role in the wait_for's check func
light mode
commandless
thats what i said yeah
Nvm misinterpreted your message sorry
in at the beginning of the code write
from discord.ext import commands
no, when a spesifc role react, that return stuffs will sent the author who ran the command with report
so?
he didn't even use it
its alright, dont be
....?
ehh let me explain
straining 😔
where did that come from
like a user did ?report,, his report is taken in a different channel,, now i added a reaction there,, so when a staff member with staff role will react, bot will msg the author/user who created that . . . .
I'm looking at your code and don't see any syntax mistake
@slate swan
oh ic, you want to check staff/mod role of the user, right?
maybe
wait no
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix = 'your prefix')
@client.command()
async def hello(ctx):
await ctx.send(f'Hello {ctx.author}')
client.run(os.environ['Token'])
refresh the webpage
ah
@slate swan
oh []?
i want staff to react there,, and it will sent a msg to the person who created report
uhh i'll try not to help otherwise i'll end up eating your brain
!d os.environ
os.environ```
A [mapping](https://docs.python.org/3/glossary.html#term-mapping) object where keys and values are strings that represent the process environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.
This mapping is captured the first time the [`os`](https://docs.python.org/3/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in `os.environ`, except for changes made by modifying `os.environ` directly.
This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
current issue is, its sending dms who ever reacting
yeah it was you did () instead of []
send it to ctx.author
my bad, maybe i am unbale to explain
was this fetched or from the bots cache
environ returns a dictionary of the environment variables
fecthed, get_guild returns None
it's not an issue from that line
show the above code
you indented wrong before
hm the guild is unavailable then, discord issue
discord/guild.py lines 450 to 455
def _from_data(self, guild: GuildPayload) -> None:
# according to Stan, this is always available even if the guild is unavailable
# I don't have this guarantee when someone updates the guild.
member_count = guild.get('member_count', None)
if member_count is not None:
self._member_count: int = member_count```
is not None
hm, why, reaction, user
to refer, when the reaction event will happen
I have to take a serious look at dpy source code because of wait_for
hmm, but the thing is that it's on multiple guilds
uhh dunno im too messed up rn
why would i lie 💀
so if it was on another guild it would work?
dunno
did you include the command prefix?
since thats necessary
bro am using discord.Client why would that matter
oh well
just tell me how can i add define a role in exchange of user? i want staff to react and it will sent to author of the main msg
why is the timeout so big
discord/client.py line 1040
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)```
that's like 1 month tf
discord/client.py line 1037
return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}'```
it just switches
#Waiting for a thumbs up reaction from the message author: ::
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('\N{THUMBS DOWN SIGN}')
else:
await channel.send('\N{THUMBS UP SIGN}')
@commands.command(
help=
"You have a 1 in 6 chance of getting shot by the revolver.")
async def russianroulette(self, ctx):
def checks(reaction, user):
return user != message.author and str(reaction.emoji) == '✅'
message = await ctx.send("Click the checkmark to join!")
await message.add_reaction("✅")
reaction = await self.client.wait_for('reaction_add',
timeout=60.0,
check=checks)
users = []
await asyncio.sleep(2.5)
async for user in reaction[0].users():
if user.bot:
continue
users.append(user)
await ctx.send('{0} has joined!'.format(user, reaction))
amtusers = len(users)
bullet = 6
cycled = cycle(users)
def next_cycled():
return next(cycled)
while amtusers > 0:
dcycled = next_cycled()
deadnum = random.randint(1, bullet)
if amtusers == 1:
print(f"{dcycled} has won Russian Roulette!")
amtusers = amtusers - 1
elif amtusers != 1:
if deadnum == 1:
print(f"Bang! You are dead {dcycled}.")
bullet = 6
amtusers -= 1
users.remove(dcycled)
time.sleep(1.5)
elif deadnum >= 2:
print(f"You are alive... for now {dcycled}.")
bullet -= 1
time.sleep(1.5)
else:
print("Error:")
#----------------------------------------```
So for some reason it doesnt cycle through the players like it is supposed to and I cant find out why
if amtusers == 1:
print(f"{dcycled} has won Russian Roulette!")
amtusers = amtusers - 1
elif amtusers != 1:
if deadnum == 1:
print(f"Bang! You are dead {dcycled}.")
bullet = 6
amtusers -= 1
users.remove(dcycled)
time.sleep(1.5)
elif deadnum >= 2:
print(f"You are alive... for now {dcycled}.")
bullet -= 1
time.sleep(1.5)
else:
print("Error:")
```??
wow
ctrl + a
if amtusers is one, do something
if amtusers is not one, do something else
else: universe exploded
but if someone uses it it will become 1/5th change of dying.
I know there are automatic roles, but I'm looking to see if it's possible to automatically assign users a role based on the current roles they have. E.g. User 1 has the giveaway role, User 2 has the event role. The intent is for users that have the giveaway role doesn't get new role and those who have event role get the new role. lmk if it is possible or if any bot do it
giveaway_role = guild.get_role(giveaway_role_id)
if not giveaway_role in member.roles:
#give him the role
just delete one of the role, ha
How can a guild be offline
💀
what?
it will give the new role?
Well Discord works in pools so some guild can be unavailable if Discord has connection issues.
you get the giveaway role by its id, then you check if the user doesn't have that role. if he doesn't, you can do whatever you want
That's how roulette works. Each time someone doesn't die the change of dying gets higher.
discord = shit ngl
frfrfrfrfr
imagine saying that on discord
ikr
cycle
Produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again.
This tag is particularly useful in a loop:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
```...
ahem ahem
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
jinja?
Oh i know I just didnt remove a bullet every time it gets shot, i just dont know why it isnt cycling
jinja is pretty awesome inside web dev
Also, ```py
elif deadnum >= 2:
print(f"You are alive... for now {dcycled}.")
bullet -= 1
time.sleep(1.5)```
hmm wait
yea that works
You have a 1/6 chance of dying, if you dont die it removes one making it 1/5 which makes your chance of death higher
But this is pretty hard coded
It still works
is it because im using time instead of the other thing
i forget what its called
is time the reason it isnt cycling
So was time the only reason it wasnt working or is there any other reasons it isnt cycling
I am using quart-discord, but I have been fighting this error for 4 hours, and I am at a lass to figure out how-to fix it.
Somewhere you are doing UserObj.discord
You have to pass on IDs to fetch_used and fetch_guild don’t you?
Also as nice as quart is it's not maintained anymore.
So, I can't use quart?
Yes, there’s really no need to have a websockets connection between the dashboard and discord
You can just know that it is unstable.
Could you show the console error?
That is the error
The error on that page is the error, the console won't say anything
Console also has errors, or did you surpress those?
A little ot question, didn't get any answer From other place
A good hosting service for a little website? Nothing too much great, just some html and javascript, no need for database either. Hosted in europe preferably
I removed them
Could you re-enable them since this doesn't really provide any info.
Yeah
All I do in the console is start the runfile
Use an Oracle VPS 👀
netcup is pretty good and cheap.
Bruh i don't want to set a vps for a single page 
I'll check it out
infinityfree (eh, don't ask)
Lol
I got their vps of 5.55 pretty good
I use a callback function
I'll just get the web hosting lel
2 bucks a month lol
Yah i can buy it, pay my rent, and buy even a brandly new ps5 lel
Waiting for the steam deck...
👀
I don't think this has anything to do with your error.
Lemme check then, but the errors go straight to the webserver
fr they got a root server for 10.80 😏
I see nothing in the files.
They go to the dashboard
What did you do that caused the error?
the webserver
Added a permission line
Does it work if you remove it?
Yea but it gives all the servers I am in
And the bot is only in 2 of them
that permissions attribute what object is that?
the users object
It will fetch the user that logged in
But if users are multiple users then how can you use permissions on that object.
Won't it be a list?
The list is usersGuilds
@app.route("/dashboard")
async def dashboard():
if not await discord_auth.authorized:
return redirect(url_for("login"))
guilds = [guild for guild in await discord_auth.fetch_guilds() if guild.permissions.administrator]
for guild in guilds:
guild_temp = await ipc_client.request("get_guild", guild_id = guild.id)
if guild_temp is None:
guild.in_server = False
else:
guild.in_server = True
member = await discord_auth.fetch_user()
return await render_template("dashboard.html", guilds = guilds, member=member, join_url = f'https://discord.com/api/oauth2/authorize?client_id={app.config["DISCORD_CLIENT_ID"]}&permissions=8&scope=bot%20applications.commands')
This is my dashboard i made once.
Then using the id as url for per guild basis
@app.route("/dashboard/<int:guild_id>")
async def dashboard_server(guild_id):
if not await discord_auth.authorized:
return redirect(url_for("login"))
guild = await ipc_client.request("get_guild", guild_id = guild_id)
commands = await ipc_client.request("get_all_commands")
cogs = await ipc_client.request("get_all_cogs")
channels = await ipc_client.request("get_all_channels", guild_id = guild_id)
_db_important_channels = '3'
_db_commands = '2'
_db_warns = await ipc_client.request("get_all_warns_guild", guild_id = guild_id)
if guild is None:
return redirect(f'https://discord.com/oauth2/authorize?&client_id={app.config["DISCORD_CLIENT_ID"]}&scope=bot&permissions=8&guild_id={guild_id}&response_type=code&redirect_uri={app.config["DISCORD_REDIRECT_URI"]}')
return await render_template(
"guild_id.html", guild=guild,
_db_important_channels=_db_important_channels,
commands=commands, _db_commands=_db_commands,
cogs=cogs, _db_warns=_db_warns, channels=channels
)
@cloud dawn would it help if you saw my /dashboard/<int:guild_id>
Idk if that helps but sure.
Then no, I just want to fix my permissions line
Hmm you need to loop it inside the guild and not do it before hand
Then I'm out of options maybe someone at #web-development has a clue.
Should I just give up?
Never
I have been on the same project for a week.
You can try #web-development maybe like Panda said
Hello I’m using message.add_interaction but I to make if statement for interaction how could I accomplish this
Trough IPC it takes a lot of structure to make it work. Idk what you have made to make this work. But people over at #web-development have much more experience regarding this.
I asked there.
Hello I’m using message.add_interaction but I to make if statement for interaction how could I accomplish this
what exactly are you trying to do with the if statement
If add_reaction == “👍”:
await ctx.send(f“ {ctx.author.mention} reacted”)
Something like this
yes
Ok thanks
anyone know how to help?
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'a' is not defined
didnt print anything as the variable a isnt defined
does anybody knows hot to make a music command without cogs?
commands in cogs and commands not in cogs are no different to each other.
and we cant help here with music bots sorry
is python a bad language for music commands?
maybe it would be easier with c# or js i dont know yk xD
hmm ture thanks
<3
you can..
you just can't help with things that use yt-dl/break tos
No?
Well, so you made the bot
And it's all ready to go
But without yt-dl would it work or no?
youll still be streaming the music without permissions no?
sure
No, because how are you gonna play music?
Okay, then get one, show proof, then you could get help.
like everyone will
for sure xD
It is very hard to get a license
not really
You gonna pay millions of dollars?
do you have a license for a song?
I'm not making a music bot so no
in case like everyone is streaming it illegal
Then why are we discussing this?
i don't know man, you started this conversation 🤷♂️
do you remember the spotify bots at the beginning of dc
Youtube actually
Yes, cause I am right for once.
they streamed music from yt which then yt changed their tos
And I am pretty sure spotify is illegal to use too
same with spotify
I wasn't 100% sure
its a music platform
the old bots got all deleted from discord because it was
Nope
Yes 😂

Want to ask YouTube then
music bots arent mainly allowed because ad revenue and copyright laws
Okay get a license and then you are right
no thanks, but fredboat has a license and it hasn't been banned yet 😳
Mkay
So you gonna spend 100000000000 hours to get all the songs in their library
all permissions to use it?
does anyone know how to fix this i dont remember
do i have to install somthing or?
youtube/spotify won't even care to be honest unless you make a premium sort of thing like rythm/groovy did
well the module doesnt have that class
and its
from discord import Embed
oh ok thanks 😭
💜
❤️
Why isn't the cooldown working?py @bot.command() async def test1(ctx): discord.ext.commands.cooldown(rate = 1, per = 3600, type='user') await ctx.send("Comlete")
its a decorator!
Yes
sorry
@commands.cooldown(1, 3600, BucketType.user)
No worries
if you imported commands ofc
Thx
How many people still use discord
I find nextcord better
why?
no you don't
you just access it with the discord module object?
Oh
its just basic imports?
Then why people importing Embed
because some people like doing Embed()
for cleaner code ig
i just subclass embed to add a default color most of the time
Oh
Why not just do
discord.Embed
personal preference
Hmm
class Klxbed(Embed):
def __init__(self, *args, **kwargs) -> None:
super().__init__(color=0x3e8fc4, *args, **kwargs)
is what i mostly do since i always want a default color
I see
@proven ore about earlier, try chunking all of the bots guilds
*args is useless
but it can see the guild tho
less chars = better code 
i agree
got another question
my token
isnt working and idk why i believe everything is done right
i think i figured it out gonna try smth
has to do somthing with my dev portal
so I have this event https://paste.pythondiscord.com/zewexoqevu which sends a msg for on_voice_state_update, is there anyway I could condense this down a bit more? I'm also not to sure about this if statement, it seems to work but I'm not sure if it's the best way to do itpy if (before.channel is not None and after.channel is not None) and after.channel != before.channel:maybe a if all() would work better?
got it to work
Traceback (most recent call last):
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Spen\Desktop\bot\main.py", line 13, in tfollow
config_file = get_config(config.json)
NameError: name 'get_config' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\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 'get_config' is not defined```
i get this when i do the command for my bot
config_file = get_config() thats the line with the error
if all((before.channel is not None and after.channel is not None and after.channel != before.channel,)):
probably this
Yeah I ended up with almost exactly that, just with a is not rather than !=, so as it try to stick with python convention
purge doesn't take a user param https://discordpy.readthedocs.io/en/master/api.html?highlight=channel purge#discord.TextChannel.purge, you'd need to add in a check instead
actually I can't do that, since when someone 'cold' joins a vc/stage there's no before channel for me to pull the ID frompy if all([before.channel is not None, after.channel is not None, before.channel.id is not after.channel.id,]):I'm under the impression I can't just check before.channel against after.channel and that I need to compare their ID's
just on some commands not all? what's the code for the command that's sending twice
it is 2 of them.
this one
@bot.event
async def on_message_delete(message):
bot.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
@bot.command()
async def snipe(ctx):
try:
contents, author, channel_name, time = bot.sniped_messages[ctx.guild.id]
except:
await ctx.channel.send("No message was deleted!")
return
embed = discord.Embed(description=contents, color = discord.Colour.random(), timestamp=time)
embed.set_author(name=f'{author.name}', icon_url=author.avatar_url)
embed.set_footer(text="caught in 4k")
await ctx.channel.send(embed=embed)
and this one
@bot.command()
async def rules(ctx):
e=discord.Embed(title = "Rules of this server", color = discord.Colour.random())
e.add_field(name = "here are a couple rules in this server", value="don't intentially join the server just to be a massive troll. It is annoying and will get you banned", inline=False)
e.add_field(name = "no child porn. nsfw, or gore", value="as long as you keep nsfw content in the nsfw channel, you will not be banned. But no child pornography, gore, etc", inline = False)
await ctx.send(embed=e)
and t's just these two that send twice? something that jumps to mind is maybe your running two instances of your bot so you should close down whatever environment/terminal your running your bot from to kill both processes. But if you have no other commands which are sending twice then maybe you have a looping issue in one of your commands but I can't see any reason for that. do you have a on_command event which might be calling the command again
cant get my embed to work
and its saying
useing await doesnt work
then how should i do it
embedded = Embed, there's no await needed
so do i just remove the await?
to only ctx.reply
embedded = Embed
await ctx.reply(embed=embedded
you don't need the await on the embed, its just embedded = Embed not embedded = await Embed
oh that what u meant
👍
what's the error, you've snipped it out
embed=embedded is what your looking for
this is an old code i used to use, used to work
async def ping(ctx):
title = "Pong!"
latency = int(round(client.latency * 1000, 0))
description = f"takes me this long to eat a cookie! {latency}ms."
embeded = await embed(title=title, description=description, client=client)
await ctx.send(embed=embeded)
this is what it used to be but for some reason i started to get errors
you declare your embed var aspy embedded = Embed(title="Filler"...)then you send it aspy await ctx.reply(embed=embedded)
embeds also don't take a client param
Can you show us your embed() function?
sure
what I'm replying to is what they sent before @final iron
Pain
ye it is just these 2
do you have a on_command event that might be calling the command again for some reason?
i don’t think so
before i had it also
from functions import embed
but then i got an error and changed it to
from functions import Embed
would that have anything to do with it
im having trouble getting it to embed idk why
I GOT IT TO WORK NVM
FIGURED IT OUT 😭
IT WAS SUCH A STUPID MISTAIKE
MB
thank you tho !!@flat solstice
sorry to say but I'm not going to much help any further, I'm not really sure what could be causing this to happen other than what I've said before an will repeat for you to reference if/when someone else helps you.
-
You could be running two instances of your bot. If this is true then it's odd that only two commands are having this issue however it could be these problem commands are your two oldest and are running on a outdated instance of your bot as well as your new instance. To remedy this try to kill both instances either by closing the terminal/program your running them from or from some program manager (like task manger on Windows).
-
You could have a a
on_commandevent which is causing the command to be re-invoked (you've said you don't think you do so chances are high you don't) -
Maybe you have a loop somewhere in those two commands that I just haven't noticed and that could be causing the issue.
If they are still around the pep compliance officer might be good to ask (I don't think they are actually a compliance officer)
np
Any big differences between nextcord and discord.py
@boreal osprey , i usually regenerate my bot token when that happens, try regenerating it and see what happens
hi, could I please know how to make it possible to put more than one role
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, id = 962640341863923772)
await member.add_roles(role) ```
discord.utils only returns the first match
get multiple roles and add them to the member
also you can just do member.guild.get_role if you're using an ID
what can I do to succeed in my intent?

i guess you could do:
role2 = discord.utils.get(member.guild.roles, id = 'whatever role id you want'
role3 = discord.utils.get(member.guild.roles, id = 'whatever role id you want'
role4 = discord.utils.get(member.guild.roles, id = 'whatever role id you want'
etc etc…
then do:
await member.add_roles(role2, role3, role4
no problem 👍
k thank
there was no error, but still does not work @cum.event async def on_member_join(member): role = discord.utils.get (member.guild.roles, id = '962640341863923772') await member.add_roles (role) role2 = discord.utils.get (member.guild.roles, id = '962707092471443466') await member.add_roles(role, role2)
Ids need to be and int not strong
I did not understand, it is difficult to understand English, can you write the correct script ?
Pls
So the id kwarg in discord.utils.get should be like id=183728283838 not id=‘1727182727’
I try to do it without the ‘’ but still doesn’t work
I am not sure then
Thanks anyway for the help sorry if I made you waste your time
It’s fine:)
Can bots no longer do await self.bot.change_presence(activity=discord.Streaming?
when I try to change it, it changes it to playing instead
if status =='stream':
await self.bot.change_presence(activity=discord.Streaming(name=f"{arg}", url='https://youtube.com/dQw4w9WgXcQ')))
embed = discord.Embed(title=' Status Changed Successfully!' , description=f'Status has been changed to **Streaming {arg}**' , color=0x9146FF)
await ctx.reply(embed=embed
is there an event that runs if any event happens
like an on_event or somthing
make a channel where the bot send a message with what happens
when event
ok
thanks
u have to have a link
lemme show u mine as refrence
@commands.command()
@commands.is_owner()
async def stream(self, ctx: commands.Context, *, text:str):
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=text, url="https://www.twitch.tv/9_de"))
message = await ctx.send(f"i've set my status to Streaming {text}")
await asyncio.sleep(2)
await message.delete()```
I do have a link if u look at the code
Ive read that you can use youtube links too
url='https://youtube.com/dQw4w9WgXcQ')))
theres not but u could do something like this
class Bot(commands.Bot):
def dispatch(self, event_name, *args, **kwargs):
super().dispatch('event')
super().dispatch(event_name, *args, **kwargs)
i dont think it can stream from youtube
how can i make a discord bot with python
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
you ask that as if it's not a long process that you need to go through
the same with learning anything
sync def status(self,ctx,status, arg, platform=None, url=None):
if status =='stream':
yt = 'YouTube'
t = 'Twitch'
if platform == yt:
await self.bot.change_presence(activity=discord.Streaming(name=f"{arg}", platform=f'{platform}' ,url=f'{url}'))
embed = discord.Embed(title=' Status Changed Successfully!' , description=f'Status has been changed to **Streaming {arg}**' , color=0x9146FF)
await ctx.reply(embed=embed)
if platform == t:
await self.bot.change_presence(activity=discord.Streaming(name=f"{arg}", platform=f'{platform}' , url=f'{url}'))
embed = discord.Embed(title=' Status Changed Successfully!' , description=f'Status has been changed to **Streaming {arg}**' , color=0x9146FF)
await ctx.reply(embed=embed)
A little help pls
to be able to stream on yt
Traceback (most recent call last):
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Spen\Desktop\bot\main.py", line 13, in tfollow
config_file = get_config(config.json)
NameError: name 'get_config' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Spen\AppData\Local\Programs\Python\Python310\lib\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 'get_config' is not defined```
i get this when i do the command for my bot
`config_file = get_config()` thats the line with the error
Reason: Command raised an exception: AttributeError: 'Bot' object has no attribute 'guild'
How do I fix this for guild.leave()?
@commands.command()
@commands.is_owner()
async def leave(self,ctx):
await self.bot.guild.leave()
Is bot defined?
there is no such thing as bot.guild
you can do bot.get_guild(id)
I am trying to make a giveaway command, and when I run it I get this error.
When you say bot.guild, it doesn't know which guild you're talking about
And it doesn't make sense for a bot to have a single guild, so they don't have an attribute for that
Now it says I need to define guild?
might help to show what you've changed
@commands.command()
@commands.is_owner()
async def leave(self,ctx):
self.get_guild(id)
await guild.leave()
oh wait have i done something funny
...
!e
["my list element"][1]
@final iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | IndexError: list index out of range
Basically, if we look at the length of ["my list element"] it's 1 and since lists start at index 0 if we try to access the element 1 it will throw an error because there is no 2nd element
@frozen patio :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | IndexError: list index out of range
idk what you need to change it to
Hmm
Can you show me what answers is?
Yes
@client.command()
@commands.has_permissions(manage_guild=True)
async def giveaway(ctx):
if ctx.author.id in blacklist:
bl = nextcord.Embed(title="You are blacklisted!", description="You have been blacklisted from Slytherin!", color=0xff0000)
bl.set_footer(text=footer)
bl.timestamp = datetime.now()
await ctx.send(embed=bl)
else:
await ctx.send('Time to start another giveaway! Answer the questions below within **`30 seconds`** in order to create the giveaway.')
questions = ['Which channel should the giveaway be hosted in?',
'What should be the duration of the giveaway? [s|m|h|d]',
'What are you going to be giving away?']
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=30.0, check=check)
except asyncio.TimeoutError:
await ctx.send('It looks like you didn\'t answer all the questions in time. Please try again.')
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f"Mention the channel properly like this: {ctx.channel.mention}.")
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send('You didn\'t answer the the question with a proper unit. [s|m|h|d]')
return
elif time == -2:
await ctx.send('The giveaway\'s time must be an integer.')
prize = answers[2]
await ctx.send(f'The giveaway will be in {channel.mention}, and will last for **`{answers[1]}`.**')
embed = nextcord.Embed(title="Giveaway", description=f"**Prize:** `{prize}`.", color=0x003fff)
embed.add_field(name="Hoster", value=f"{ctx.author.mention}", inline=False)
embed.add_field(name="End Time", value=f"Ends in **`{answers[1]}`.**")
embed.set_footer(text=footer)
embed.timestamp = datetime.now()
my_msg = await channel.send(embed=embed)
await my_msg.add_reaction('🎉')
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await channel.send(f'Congratulations to {winner.mention} won **`{prize}`!**')
@commands.command()
@commands.has_role(950613237739708476)
async def game_s(self,ctx):
guild = ctx.message.author.guild
Signed_up = ctx.guild.get_role(950611405986480208)
channel = self.bot.get_channel(950613102100086854)
if ctx.message.channel.id == 950613102100086854:
for members in ctx.guild.members:
for member in members:
if Signed_up in member.roles:
print(member)
await member.remove_roles(Signed_up)
await member.add_roles(ctx.guild.get_role(950611491101483089))
await self.bot.get_channel(950614806702985296).send('The game has started <@&950611491101483089>')
elif ctx.message.channel.id != 950613102100086854:
await ctx.send(f'{channel.mention}')
2022-04-11T23:56:25.943189+00:00 app[worker.1]: File "/app/game_shift.py", line 17, in game_s
2022-04-11T23:56:25.943190+00:00 app[worker.1]: for member in members:
2022-04-11T23:56:25.943216+00:00 app[worker.1]: TypeError: 'Member' object is not iterable
what am i doing wrong here ive been working on this for a while now
you just need to do for member in ctx.guild.members without the 2nd for loop
that didnt work either the bot could only return itself as a member and didnt see my account or my alt
it didnt give an error it just would only check itsef
intents off maybe?
is that a new thing ive seen that twice today
your bot needs to be configured to view members in the guild
it has admin of the server
does that work with 3.7.0
yes? https://discordpy.readthedocs.io/en/stable/intents.html#where-d-my-members-go see this specifically
but I encourage you to read what intents are as they are important to understand
alright thx ima go read up on it
ive never heard of this and this code use to work like 4 years ago so maybe thats the problem
sounds like it