#discord-bots
1 messages ยท Page 927 of 1
Uh yeah that's a problem
.
Replit is trash for bots
Get rid of the "for bots" part
Lol true
Yeah i did check the docs it's just that my brain thought intents were already enabled
Alr, np
agrees
I'm gonna need help, but I'll wait if someone's still being helped
ask your question...
just ask
I am using MongoDB for database. Each document will be a user's profile. It will have fields like user_xp, user_point, etc
But, not all users will have the same fields at the same time. If, say, they want to check their server points, they'd do $points. Then, it would check if the user has user_point field.
The problem is with the checking. This is my code so far, and it just won't work.
It would always end up with "you may only claim once a day"
I thought, if MongoDB do the lookup and finds nothing, it will simply return null. So I tried checking is None. It still doesn't work
Any1 knows how to use link buttons with persistent views?
yes
Umm how?
you just do...?
there shouldnt be anything special with combining url buttons and persistency
make the view -> add the button -> make it persistent
There is am not able to
Ill send my code tell me how to do it
class help_class(disnake.ui.View):
def __init__(self):
super().__init__(timeout=None)
disnake.ui.button(label="Abc",url="", custom_id="help:1")
disnake.ui.button(label="Def",url="", custom_id="help:2")
- use motor
- tl;dr?
!d discord.ext.commands.Bot.add_view pass in the help_class here
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
I need to know how to make it so that if there doesn't exist a matching document like this, then...
Ik abt the add_view class l
Am talking abt this code it aint working
there's the link.py example on github which shows how to use the Button class for creating link buttons https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py#L22-L32
examples/views/link.py lines 22 to 32
class Google(discord.ui.View):
def __init__(self, query: str):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
query = quote_plus(query)
url = f'https://www.google.com/search?q={query}'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label='Click Here', url=url))```
Umm let me try that one
do ```py
res = collection.find_one({"user_id": author_id})
if res is None:
...
None*

With @commands.has_role how do I make it do something if they dont have the role?
erorr handler

That raises a commands.CheckFailure exception iiirc, just handle it inside your error handler (if you have one)
So Im assuming the error would be commands.MissingRole ?
yup
Gotcha ty
@hushed galleon @boreal ravine Thanks for help got it working!
Btw the links button are already persistent no need to make them persistent
It still does not work. It still ends up at "You may only claim reward once a day"
Show updated code
Ouch, there's exception raised
res = collection.find_one() #fetch the user
if res:
return await ctx.send("U have claimed your daily reward")
''' write your daily reward code and update the db '"```
I need to check if some fields exist or not on the document we're looking too
example_returned_from_db = [{'id': "12356654", 'extra': "value"}]
if extra in example_returned_from_db:
return await ctx.send('extra is in the user')```
You asking me?
Don't you do that when you insert the document
u dont need to check it lol
No
you can make more keys using the update_one func
Ohh ok
Hmm, I might do this
No, because it's only created if a user does it the first time
This is so if I make new features that require fields, I won't forget adding it
Is there some way for the bot to check if it misses any permission?
it raises a discord.ext.commands.BotMissingPermissions exception
Aha got it thanks!!
..
exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the botโs member lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
It depends on your case
There are at least 3 ways but they relate to different situations
hey guys, I'm having issues with the bot not running tasks in the background >< the idea is to iterate through names inside of a dictionary then make a background task for that specific item. issue is, it gets stuck on the very first item and doesn't proceed to the next
itemNames = [item1, item2, ..]
async def main():
for item in itemNames:
await createTask(item)
async def createTask(item):
await bot.loop.create_task(backgroundTask(item))
async def backgroundTask(item):
while True:
print(item)
await asyncio.sleep(5)
# my output:
# item1
# item1
# ...
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Use this for background tasks
Examples in docs
And this one gets stuck because of while True loop (why would you even want to print something forever)
I looked at this particular one but mine doesn't seem to work the same https://github.com/Rapptz/discord.py/blob/master/examples/background_task_asyncio.py
...
async def setup_hook(self) -> None:
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
...
Aha got it Ill fix that with error event
Umm I just want my bot to like say "Hey I miss this permission pls enable it"
For that the error handler handling the BotMissingPermissions is enough
this should pull the relevant embed for this channel?
Umm how to get which permission is missing?
Wth is currentEmbed
a dictionary
I think it's error.missing_permissions
theoretically in format {channelid : embed}
client.currentEmbed[ctx.channel.id] = await ctx.send(embed=embedVar)
!d discord.ext.commands.BotMissingPermissions.missing_permissions
The required permissions that are missing.
This @inner epoch
It puts a message not an embed
send returns the message
Your embed is embedVar
O nvm didn't see
i am constructing an embed, and assigning it to the embed parameter of a message
then later i am trying to pull the message (which only has an embed) and change what the embed is within the message
Try printing the dict
but it would appear that somehow it doesnt have an edit param
Aha let me try that!!
Aha got it thanks a lot man!!
the dict has a none as the channels data
which is odd as before makign it construct a dict to make it channel relative, it was properly setting the value
{951924364339716176: None}
Um yeah
thats the channel id but obviously not the embed
And you define it exactly like this?
this
@glacial echo u completed the command yesterday?
Are you sure the send isn't raising any errors
the send isnt erroring and is sending the embed in the channel
Try storing message id as a value in dict and then fetch it when needed
m = await ctx.send(...)
client.current_embeds[ctx.channel.id] = m.id
...
# when the fetch
m = await client.get_channel(channel_id).fetch_message(client.current_embeds[channel_id])
await m.edit(...)```
nope
And you define the client like commands.Bot right?
Anyway try this method
!d disnake.Client.get_channel exists
get_channel(id, /)```
Returns a channel or thread with the given ID.
it returns a Message object
it does 
yeah i know it should but its returning a NoneType
is the message sent or not?
yes
try printing the object
Channel*
it sends a message, then fails to return that object
huh?
Eh, what u talking about
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
get better
ยฏ_(ใ)_/ยฏ
lol
disnake dies in its own world sometimes ๐
@maiden fable any help?
yeah
maybe my internet is just being shit right now?
@glacial echo mind showing code?
Doesn't matter
try updating disnake ๐
would it be possible my internet being slow means it is moving on in the code before it actualyl gets a returned ID
i installed it literally last night
Nah
welp
can I see some code?
that happens locally ig
||but......||

can i just link my github for it?
yeah do that
or the file url ๐

Also the repo is private
A file can still have multiple lines, soooo
just tell the line number huhhh
Prolly
Might as well give the line link instead
damn ig its fixed
which file
dicord_game_bot.py line 57
async def startGame(ctx, gameID: int = 1):```
why does github return 404 when the status is actually forbidden access 
Cz it wanna hide that the repo is private
What's the issue?
Like, what doesn't work
so, when you send a message for the game it cant edit the embeds
becasue for some reason the message object within the dict is a NoneType object and NOT a message object
you made the stuff more complex than they should be
Haha u need to do ctx.original_message()
almost definitely
!d disnake.Interaction.original_message
await original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
Here is a table with response types and their associated original message...
Totally me in the first try
can relate cool
After ctx.send
In the next line: var = await ctx.original_message() replacing var with the original variable
not sure i understand ???
OH LMAO THAT WAS A SLASH COMMAND
Name variables properly for god's sake
It should not be ctx, it should be something like inter
await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
If the interaction hasnโt been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").
Note
This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_message()`](https://docs.disnake.dev/en/latest/api.html#disnake.ApplicationCommandInteraction.original_message "disnake.ApplicationCommandInteraction.original_message") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if youโre sending a followup message.
Returns nothing
Can someone help me with slash commands in my cogs file using the pycord library
Hm?
MY BOT WORKS LETSS GOOOO
i just got my friedn to play it and we had the first successful game
this is incredible
now
i either add a random restriction to the words each round and implement a gameover condition, implement a universal game end command, implement the gamemaster role stuff, OR fuck off and code hangman into the bot cause it sounds fairly easy
is there a library that will generate a random word
idk if this supports it
i found one
random-words is a library
time to implement the base of a hangman game
if i get the UI for it working somewhat ill go to bed
hmmmm it says its not installed but it is
https://www.toptal.com/developers/hastebin/qipereyiza.sql wth is this uhhh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this isnt seeming to work
it seems to not be importable in the way the documentation says
Just use some hangman API pretty sure there are some
what's yr disnake version
!pypi hangman
@glacial echo might as well see its source code ๐
who knows ๐
Hmm
Ah I got the issue
See the first line
relative imports goes brrrrrr
give it a parent package name
thats no fun now is it
and wont get me marks
>>> from dis import dis
>>> dis(__import__("random"))
Istg don't run this code as long as u don't want to see yr console spammed with lines
man
๐ when I changed from random to disnake
why is my imports not working
๐คฃ the memory fucked up
uhhh I thought I'd make a bot
But it bored mke as soon as I wrote commands.Cog
so leave it uh

๐
@bot.event
async def on_wavelink_track_end(player:wavelink.Player, track: wavelink.Track, reason):
ctx = player.ctx
vc : player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song= vc.queue.get()
await vc.play(next_song)
await ctx.send(f"Playing: {next_song.title} rn :)")
@bot.command()
async def play(ctx: commands.Context,*, search: wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not ctx.author.voice:
return await ctx.send("Pweasee join a VC <3")
elif not ctx.author.voice != ctx.me.voice:
return await ctx.send("Pwease be in the same VC <3")
else:
vc : wavelink.Player= ctx.voice_client
if vc.queue.is_empty:
await vc.play(search)
await ctx.send(f"Playing: {search.title} rn :)")
else:
await vc.queue.put_wait(search)
await ctx.send(f"Added {search.title} to the queue <3")
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send("Pweasee let me join a VC <3")
elif not ctx.author.voice:
return await ctx.send("Pweasee join a VC <3")
elif not ctx.author.voice != ctx.me.voice:
return await ctx.send("Pwease be in the same VC <3")
else:
vc: wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
return await ctx.send("queue is empty :(")
What this should do:
add a song to the queue , and play when the previous song finishes
What bug i get:
Upon adding a song, ignores the queue system and just plays it
I get this error in console:
Ignoring exception in on_wavelink_track_end
wavelink.errors.QueueEmpty: No items in the queue.
cannot help with music bots, sorry
!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)
thanks for the honors
But uh is wavelink related to those
Yea
Ok
More or less, both wave and lava link is related to ytdl directly or indirectly
wavelinks github mentions spotify not youtube
Still against ToS
afaik, spotify doesn't allow it
Yup
ah
why everyone wants to make music bots ๐
cause youtube killed all the good ones
man why cant i download and use any modules
this is so stupid
Wym
i cant use the random-word module
any error?
it keeps saying it isnt a module reference
just listen to spotify
Indeed
Restart IDE
!pypi random_word
Wrong python version?
Use a venv and install there
U got two?
Venv good ๐
Hmm I never used that as such lmao
that library says it wokrs with 3.10 which im using
No I mean
Venv is very convenient
how do, how much work woudl it take changing to using that
wait, can u do py -3.10 -m pip install random_word in the command prompt?
A mere 2 min tbh
Is there another way to keep my bot online other than using Replit
u gotta host it at least anywhere
py -m venv venv```
CTRL + SHIFT + P -> Select Interpreter -> venv
Easy
dont use replit for hsoting at all
Oh my bad
you could selfhost or check pins
random_word*
And yeah update pip
pip install -U pip```
remove the s
whats updating pip do
Pip 22.0 has nice loading bars ๐
Also before 22.0 there were issues with some modules installation on 3.10
If you tried to install something like scikit you would get weird wheel errors
Hmm idk about that
Better for people like me who tend to forget to update it
imagine if you could update everything via pip
related to Python*
I just did sudo do-release-upgrade -d and it updated my ubuntu to 21 with py 3.10
Cool
NOOOOOO
mind showing yr code?
But uh it might require some first usage setup
if im doing anyhting more installign and setup stuff im doing it tomorrow tbh
its late already
Like editing regedit
stop
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hmm and module not found error?
ye
Can u see yr selected python version from the bottom bar?
No
Oh yeah there might be issues with modules resolving if you have multiple pythons installed
From here
At the vert bottom
that's why you should use venv
Oh well
yea yea i get it venv gud
Windows Store goes brrrrrrrrrrrrrr
Sus
most prolly that is the issue
Why not just https://python.org
@glacial echo delete that python version and install python 3.10 from https://python.org
damn u
Ah
Kinda fast
then do py -3.10.2 -m pip install disnake
i had both
in the cli
remove the windows store one, its useless
dunno how tbh
it autoinstalled at some point
Check your applications installed, search python and delete all pythons, then just do setup as hunter said and don't forget to check "add python to PATH"
Yea
ok so windows wont let me uninstall
๐ณ
And this way, u will remember that Python from Windows Store fucked up my sleep schedule once so I won't install it ever again
A blue popup?
SmartScreen or smth like that, right?
SmartScreen usually pops up when you try to actually install
Yea, click on More Info and Run Anyway
no, a window titled unexpected error
Huh show
nice
man why is this so broken
client.leadWord[ctx.channel.id] = rw.get_random_word(minLength=5)
for i in client.leadWord[ctx.channel.id]:
client.leadWordPoints[ctx.channel.id].append("_")
fuck this im going to bed
Haha gn!
i know iโm too tired to program stuff when i mess up this bad
wai i could do client.leadWordPoints[ctx.channel.id] = โ_โ * client.leadWord[ctx.channel.id].len()
or what we the length function is
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**."
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
await Channel.send(Text)
@client.event
async def on_reaction_add(reaction, ctx, user: discord.Member, role: discord.Role):
ID = 956441072916107304
red = discord.utils.get(user.server.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await ctx.send(f"Done :star3:", delete_after=0.4)```
this is my code and the error is:
wait ill send ss
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnโt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
It doesn't take ctx and role.
Yes
It only takes py async def on_reaction_add(reaction, user): notฬ```py
async def on_reaction_add(reaction, ctx, user: discord.Member, role: discord.Role):
the event doesnt take ctx and role args
k lemme check
No?
The message is sent with reaction but role is not added .
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnโt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
Read it
It takes two arguments, reaction and user.
how?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
The reaction emoji. May be a custom emoji, or a unicode emoji.
Check if the emoji is what you want, if so add the role to the member.
if reaction.emoji == "emoji":
await user.add_roles(role)
str(reaction.emoji)
I have this in my code
In the docs it says it returns Union[Emoji, PartialEmoji, str].
ikr, you do know that it returns an Emoji object
But it says str too
Still the bot is not giving the role
.
Removed everything after ctx in9th line
k wait
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**."
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
ID = 956441072916107304
red = discord.utils.get(user.server.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await ctx.send(f"Done :star3:", delete_after=0.4)```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
No documentation found for the requested symbol.
then what should I do?
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**."
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user, ctx):
ID = 956441072916107304
red = discord.utils.get(user.server.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await ctx.send(f"Done :star3:", delete_after=0.4)```
updated code with error:
Instead of user.server do reaction.message.guild.
Instead of ctx.send do reaction.message.channel.send
aaaa
Just delete the last character.
after guild .roles, "red" right?
Wdym
I suppose
Delete the last character on line 27.
So its time_dict[unit?
:redf: ?
Changed it ._.
No, but there's an invisble character at the end
can bots use animated emoji?
Why return after return
Oh
Yup they can
Yes
and how do bots using custom emoji work, is it emoji that the owner could use?
The last return will never be reached
Yes,<a:emojiname:emojid>
But the bot should be in the guild where the emoji is from
You mean emoji that can only be used by certain role?
Bots can use any emojis from the server they are in with the format RyanDang#0001 sent
ah so ideally youโd make a server for your bot to have emojis it might use in its own UI
Yes
I have it in my private server with my bot in it
Same
i meant like, do bots have access to emoji of the server their in or that their owner is in, and do bots have nitro or only if the owner has nitro
Yes,I personally use a private server where my bot emotes are stored
Ah you mean that
It doesnt need nitro,even if the owner doesnt have,the bot will work
Bots are basically nitro users but without banners and tag customisation that's it
Ofc we can't say they all have nitro
Basically they have access to things that are accessible for humans only with nitro
why dont bots have custom banners
@vale wing Exactly,you are correct they dont have the customization and stuff but they can use custom emojis
wait bots get anim pfp?
Dude
No
ah
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Still
The role is not added
And the on_ready event when my bot says itโs online itโs not there
No errors on reaction or code
Show your new code agian
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**"
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
ID = 956441072916107304
red = discord.utils.get(reaction.message.guild.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@slate swan use the format he showed
@client.event
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**"
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
ID = 956441072916107304
red = discord.utils.get(reaction.message.guild.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)
It comes the same way ._.
With the py
print(hello*10)
Oh
Like that
py stands for python format.
@client.event
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**"
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
ID = 956441072916107304
red = discord.utils.get(reaction.message.guild.roles, name="red")
if reaction.message.channel.id != ID:
return
if reaction.emoji == ":redf:":
await user.add_roles(role)
await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)
Yes
I was viewing from my iPad, sorry lol
When you run that code, is your user id 956441072916107304?
My?
Yes
Nope
Well then that code won't work for you.
Oh I can't read
Sorry
Um?
Nvm, are you in the right channel when adding the reaction?
Yup
The message is sent in color roles channel
With reaction
But no role is given
This apparently does not work
cool
Try adding some print statements, then you'll see where it fails.
huhh
Even though there's already one
sten help ๐ I'm going to play
I actually wonder, when we pull out collection.find(), I wonder how I should carefully extract the data
I thought it would generate something similar to a Python dictionary
Correct me if I'm wrong, but I want to see if the field user_id exist. author_id is the value of author's ID
This is author's id
I see. Alright, my goal is to check if userData has a field called user_id
I think I know what you meant
But then I would probably have to use another aproach
if author_id in userData:
# not
if "user_id" in userData
Wouldn't it just verify if we're pulling the correct data?
Or you might want userData["user_id"]
whats the problem
But wouldn't this statement refers to the value of user_id? which would be that number of 34190878901743
So I am using mongodb for my discord bot database.
Oh I forgot it was a dict, my bad.
nice
When someone sends something on to any channel, the bot will obtain the user's ID and then check on to the database to see if this user already has a "profile".
hmm
If not, it will create one. This is handled by this part of the code
You know what, even the first half part of the code seems odd, let me fix that real quick
I think you want this: ```py
if userData["user_id"]:
Does that code ask if userData has user_id field?
It checks if the userData has an user_id in it.
as a key not a value right?
It accesses the key, and check if there's a value in it.
Added print(โdoneโ) after if reaction.emoji == โ(the emoji)โ:
Didnโt typed emoji name because it was gonna be replaced by :redf:
Did it print?
Nope
In that case it returned because you're in the wrong channel.
I'm stripping everything out. Beginning from here, first, I want to check if there exist a document already for this user. I have the value of author_id which contain user's discord account id.
Assuming I do a lookup based on the account id, and if the user is brand new, there shouldn't be any result coming back. How do I make that logic?
Oh, you are using != and not ==, so this command will only work if you're in the wrong channel. @slate swan
So if I use == it will work in the correct channel?
You could use userData.get("user_id", None), then it would return วธone if no member is found.
I think so.
What does that None mean?
It returns None if the user_id isn't in userData.
Also you might want to ask in #databases
@slate swan uwu
You shouldn't ping people without reason
it has no attribute get
Oh, I thougt userData was a dictionary.
It's saying it's a cursor
Well then check #databases
But all the examples on geeksforgeeks is like this
Still the role is not given
Even the bots role is above color role
Does it print anything?
Nope
ik :P
Try adding another printstatement at the very beginning of on_reaction_add
mhm k
When the bot is successfully online it says โhiโ
And on reaction it says the same
I added it after on_reaction_add next line
Alright, can you send the current code?
k wait
@client.event
async def on_ready():
Channel = client.get_channel(908976132550950952)
Text= "React Below To Get the color role **Red**"
Moji = await Channel.send(Text)
await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
print("hi")
ID = 956441072916107304
red = discord.utils.get(reaction.message.guild.roles, name="red")
if reaction.message.channel.id == ID:
return
if reaction.emoji == ":redf:":
print('done!')
await user.add_roles(role)
await reaction.message.channel.send(f"Done :star3:", delete_after=0.4```
Does it work in the on_ready?
The one on_ready event I have in the start of code is not working
Which always prints (bot is ready)
Do you get any errors?
Nope
No errors in console
Wait when does it print that?
I can't see the print statement.
Not in the code I sent
It is in the whole code for the code
Uh, is it more code in the on_ready event?
Ok lemme explain
I have one on ready event at the very start of code for changing bot status and printing that the bot is online
And
The one I sent is this code is different
You can't have multiple on_ready events.
Only one.
Same with all other discord events.
Including on_reaction_add.
So Iโll have to remove the bot on_ready?
Wonโt that make the bots status = nothing
status message*
bot status is set with change_presence .-.
Is on_ready needed for it?
https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.is_news
what does this give me? anouncements?
nope, you can change it whenever in the code
this returns True if the channel is a news channel, else false. News channel are channels like #pyweek-33-announcements you can identify them from the megaphone

https://www.toptal.com/developers/hastebin/qipereyiza.sql wth is this uhhh
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.

do you added a folder in your cogs folder?
no..
Mhh can you past the screen or schema of cogs folder?
I have project about Twitter bot for reply and retweet tweets but i didn't find something to help , do you have any ideas?
well that's strange, also i saw that there are two coro which aren't awaited
meanwhile you could try something like this for the cogs:
COGS = [path.split("\\")[1][:-3] for path in glob("./lib/cogs/*py")]
I've checked, I didnt even write a single function, all the functions are passed as of now 
that are anouncements channels
bruh
wut...
create a COGS list for all the file which ends with .py in cogs folder
uh I see
nvm, I found the issue
gg
lol

.
maybe the problem could be that the bot and the setup where you load the cog have a different loop, or you pass that loop to your bot?
imma try what you said
nice
it really was that? xD
When I used a list comp instead of a simple for loop for loading extensions, it worked 
interesting
this looks clean though

@client.command()
async def add(ctx, args):
user = ctx.message.author
role = discord.utils.get(user.guild.roles, name=agrs, permissions=Permissions.all())
await user.add_roles(role)
await ctx.send("Role added")```
error
```py
Ignoring exception in command add:
Traceback (most recent call last):
File "C:\Users\GUDDU\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\GUDDU\Desktop\Program\Projects with my friends\hack.py", line 30, in add
await user.add_roles(role)
File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\GUDDU\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\GUDDU\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\GUDDU\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: AttributeError: 'NoneType' object has no attribute 'id'```
help me out
I suggest to you to study this https://www.toptal.com/developers/hastebin/wuzojejafu.py
i think i will add a repo on github soon where i'll add this really simple and very usefull setup, i use this base for all my bots
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
nvm the database import and other things which will not be included
tell me youre conceited without telling me youre conceited
D_D
utils.get() take a single discord object as parameter, you are giving him a list of objects
Python problem, need help.. It says in my dict, key "user_daily_time" does not exist..
But it's there
Lol are you sure that you are taking the value at your_dict["key"]?, read better your code
it is not saying that your dict doesn't have it, the error is saying that dict object has no attribute user_daily_time
BRUH
Sorry, and thank you
2 AM brain is hard..
not that 12pm brain would do much anyway
np
async def get_logs_channel(self, guild_id):
data = await self.bot.db.fetchval("SELECT channel_id FROM modlogs WHERE guild_id=$1", guild_id)
if data:
return self.bot.get_channel(data)
async def create_webhook(self, guild_id):
channel = await self.get_logs_channel(guild_id)
return await channel.create_webhook(
name=f"{self.bot.user.name} " + "Logging",
avatar=self.bot.user.avatar.url,
reason="For logging"
)
'NoneType' object has no attribute 'create_webhook'... i cant send the webhook, ik what this error means but when im fetching that channel it works.. but it wont send the webhook
im sending the webhook like this:
webhook = await self.create_webhook(ctx.guild.id)
await webhook.send("content here")
print the channel var in your create_webhook function
let's see if it get the channel
Can anyone pls help me
i am getting error in heroku in loading cog
Unable to install C enchant library
even though pyenchant is present in my req.txt
Dude, it works. My goodness I am happy. I can finally sleep. Thank you kind soul
don't use heroku .-.
Guys I want to make a discord bot with Python that will kick members with a command. I made it, but when I am kicking someone I want the bot send a message. How to do that?
@sturdy cloud Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Ops mistake :)
well if it is a command then you have a context, and the context has a send method, so just use it
._.
ok tnx :)
startswith first arg must be str or a tuple of str, not bytes
this is the error it printed
i'm not understanding .-.
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality.
how to know which guilds our bot is in?
do i need 320 kbps audio for a discord music bot ?
no
since channels are literally just 128 kbps max
no i have music bot and works fine
so using 128 instead of 320 makes no difference ?
without boost
small quality change nothing else
wait can kbps go higher when boosted ?
ill keep it on 64 kbps anyways
and a bit clearer to our ears
keep it as is
so 128 completely fine ?
tbh
thank you ๐
how to know which guilds our bot is in?
guild count or guild names
names
uh
ok lets try guild count
servers = len(client.guilds)
print(servers)
[guild.name for guild in bot.guilds]
or list(map(lambda m: m.name, bot.guilds)) which is quicker
why?
and?
he wants the names
Doesn't hurt having a list either.
you have absolutely no logic or reasoning, you're just trying to cause trouble
Be nice
you cant print a map object, you can print a list object
and...? he wants to see the names not a map object
not if you print the map object
Why are you even arguing about this?
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0 1 2 3 4 5 6 7 8 9
Error?
there is no error
The argument might override the command name.
Also, no need for setting the embeds title to nothing, it is automatically None.
And why do you have pass_context passed into the command?
@client.event
async def on_member_join(member):
mbed = discord.Embed(
colour =(discord.Colour.magenta()),
title = 'Welcome Message',
description = 'Welcome{member.mention}, enjoy your stay!')
await member.send(embed=mbed)
why its not working
someone tell me where am i wrong
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!intents also u r missing a closing brakcet
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.
And you need to make the description in the embed to a f-string.
Yea thhat too
Poeny, can you please use the code format?
i am really sorry , can plz tell me how to ? i am new to this
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@client.event
async def on_member_join(member):
mbed = discord.Embed(
colour =(discord.Colour.magenta()),
title = 'Welcome Message',
description = f"Welcome{member.mention}, enjoy your stay!")
await member.send(embed=mbed)
thank u , i now learned it
now sm1 tell me whats wrong
Great, now fix the intents and make it a f-string.
like this?
Yes, and the intents if you don't already have them.
what intents? i gave my bot perms , that one?
!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.
Read it
import os
import random
import requests
import json
import discord
from discord.ext import commands
import keep_alive
client = commands.Bot(command_prefix ="%")
isnt it enough?
No, you need to add the intents.
i did
Can't see it
bot = commands.Bot(command_prefix="!", intents=intents)
import os
import random
import requests
import json
import discord
from discord.ext import commands
import keep_alive
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="%", intents=intents)
o.O
Don't define bot and client twice.
Remove the client line.
And don't import commands twice either
now?
Sure
Test your command
where?
He edited the message
Also, is keep_alive a module?
a local python file to keep his replit alve
Then shouldn't it be like: ```py
from keep_alive import keep_alive
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def main():
return "Hello, I am running!"
def run():
app.run(host="0.0.0.0", port = 8080)
def keep_alive():
server= Thread(target=run)
server.start()
we know
Did it work?
works fine.
no errors its the issue
- Running on http://172.18.0.118:8080/ (Press CTRL+C to quit)
172.18.0.1 - - [24/Mar/2022 10:35:30] "GET / HTTP/1.1" 200 -
WE HAVE LONGED IN
Nicely spelled.
import discord
from discord.ext import commands
import json
class Setlog(commands.Cog):
def __init__(self, client):
self.client = client
with open('log_channels.json', 'r') as f:
log_channels = json.load(f)
@client.command()
@commands.has_permissions(administrator = True)
async def modlog(self, ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('log_channels.json', 'w') as f:
json.dump(log_channels, f)
await ctx.send(f'Mod log set to {channel}')
def setup(client):
client.add_cog(Setlog(client))
``` I am not sure how to do this but how do I make a command to set a log channel
In cogs you do commands.command.
And the command shouldn't be inside __init__.
๐คฃ noticed only now
BTW does this work?
Yeah, indent it once.
Not sure
1 tab back or
after indenting it inside the init
๐
I did
import discord
from discord.ext import commands
import json
with open('log_channels.json', 'r') as f:
log_channels = json.load(f)
class Setlog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(administrator = True)
async def setlog(self, ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('log_channels.json', 'w') as f:
json.dump(log_channels, f)
await ctx.send(f'Mod log set to {channel}')
def setup(client):
client.add_cog(Setlog(client))
!indent
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
Haha
was just a dumb mistake
still same error
show
whats the git pull output
pull
did
show the pul outpu
then push
ah, u edited yr code locally before pushing which has resulted in errors
I never had this before lol
basically the code in the remote is different to your local
so you have a couple options
either you stash all the code, pull and then pop it
which is probably the best way
or you reclone it and move your files
or you can just stash it and not pop it
so how to fix it
Lmao
git stash
git pull
git stash pop
git push```
whats git status output
it tells you what to do; do git add .
yes
I usually do git add *
continue doing this
did you do git stash?
ye
what was the output to git stash
whats the full output to this
thats it

You can just add a force flag at the end of tat
wdym
yep ty
my small brain does not allow me to interpret the meaning of this emoji

๐ You do know forcing isn't gut, right?
well, it is what it is
that was my point
mhm
dont know what you mean by that 
I ain't explaining anything I hate git anyways
learning git would have been a better investment than hunai
I know 3 things about it: push, pull clone
Just don't push commits until you're 100% happy with them
Rest all, VSCode handles for me
๐ I always push to the ui branch and tries to merge ui into master but idk what I do wrong it just doesn't happen
you can find the docs online, you dont need to watch any videos or anything 
I know
welp, your choice
I never really had to use any other commands, so never really saw the docs as much
branch? 
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
bot.users
Wasn't that obvious tho
it was, I was just bored
so i asked a question that was completely irrelevant to me 
Lmao
When I do .setlog #channel my github doesn't update. How do I gotta do that when I use github heroku
why would the repository update
a database?
yeah but idk how
Not sure if this is python related question
whats your limitations?
I use heroku with github
JSON !!!!!= database
this channel is discord-bots
Those don't even stay near
and json database is easy to make for beginners,
no one starts with sql
And his question is kinda not
Well I don't know how to do that with a discord bot, set a log channel
Don't even use such term "json database", there are "json-like databases" but a bunch of json files or a single json file can't be considered a database
You mean github events?
stop
That's implementable with webhooks, you don't even need a bot
Oh
You could make an architecture in which all the queries would go to one function and that function would always log what it is supposed to
Yeah I got no clue to do that
async def exec_query(query, ...):
await db.execute(...)
log.info("Query executed: %s", query)```
If your storing data to a file in Heroku, it will refresh the state of the file back to how it was on the push, this is because heroku uses an ephemeral file system
In order to store data on heroku that changes, youโd need a database hosted outside of heroku
yeah but idk how 
Maybe it provides separate databases
moneh moneh
But basically just use a VPS
Digital ocean free 100$ for two months, amazon AWS free server for a year
const express = require("express");
const app = express()
app.listen(3000,() => {
console.log("project is running!")
})
app.get("/", (req, res) => {
res.send("Hello world!");
})
const Discord = require("discord.js");
const Client = new Discord.Client({intents : ["GUILDS", "GUILD_MESSAGES"]});
client.on("message", message => {
if(message.content === "ping") {
message.channel.send("pong");
}
})
client.login(process.env.token);
Vultr has free options as well but they aren't really "free" as they charge you to activate bonus
discord.gg/djs @slate swan
express and djs together
so i have this in my on_message and it basically reply every time it got mention and i wanna ask if there's anyway i can except the @everyone @here cuz it automatically reply whenever we mention the @everyone @here
check for it's content
here's the code
if client.user.mentioned_in(message):
answers = ["yes", "no"]
await message.reply(random.choice(answers))
Then add and check if @everyone and @here isn't in there.
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
check if the message content is only the bots mention format ig ```py
if message.content in ('<@id>', '<@!id>'):
...
Why is it error?
import os
import discord
from discord.ext import commands
from discord.utils import get
from keep_alive import keep_alive
from discord import Intents
intents = Intents.default()
intents.members = True
client = discord.Client()
client = commands.Bot(command_prefix="!", intents=intents)
client.remove_command("help")
@client.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.channels, name="general")
await channel.send(f"{member.mention} has just joined the server!")
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
keep_alive()
client.run(os.getenv('TOKEN'))```
Oh okay
Still error
what's the error though
File "main.py", line 27, in <module>
client.run(os.getenv('TOKEN'))
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
- Running on all addresses.
WARNING: This is a development server. Do not use it in a produc - Serving Flask app '' (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: off
- Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment. - Running on http://172.18.0.97:8080/ (Press CTRL+C to quit)
Traceback (most recent call last):
File "main.py", line 25, in <module>
client.run(os.getenv('TOKEN'))
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
ah ok
from dotenv import load_dotenv; load_dotenv()
import os
import discord
from discord.ext import commands
from discord.utils import get
from keep_alive import keep_alive
from discord import Intents
from dotenv import load_dotenv
load_dotenv()
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents)
client.remove_command("help")
@client.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.channels, name="general")
await channel.send(f"{member.mention} has just joined the server!")
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
keep_alive()
client.run(os.getenv('TOKEN'))``` Is this right?
sure
But still error
Do this:```py
client.run(os.getenv["TOKEN"])
Okay
It should be with [] not ().
Traceback (most recent call last):
File "main.py", line 27, in <module>
client.run(os.getenv["TOKEN"])
TypeError: 'function' object is not subscriptable
Error
Unpythonic smh
i think you're thinking of os.environ
__import__('dotenv.load_dotenv'.__str__()).__call__() is this better?
@slate swan thank u it works
What works?
do anyone tell me how to send welcome msg in the chanel
Do i have to use this?
the bot send welcome msg in dm
Didn't you already have that?
in dm it can but not in channel
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Or just use a 2nd line








