#discord-bots
1 messages · Page 1097 of 1
You sended the ss but you are already working in the Message object so you can just use MessageReference so I have no clue as of why you are making this and where there is an issue.
if Message object (self) has a reference, I want to get the Message that represents that reference
essentially the Message that was replied to
or None if there's no reply
are you with me?
I want to get Message object of ^^^^^^^ the message above
if I do getch_reference_message on ---> THIS <--- Message
So aka the replied message.
Oh i get it lmfao

Does this work? Or do you want a better/ shorter version?
It looks pretty solid besides from the fact that the typehint is wrong and it could return a DeletedReferencedMessage as well.
it does work
it cant return that, look at the last line
Unless the reply was deleted then this would fail.
Oh yeah.
I fully understand it now of you want me to explain it fully.
yes please
I assume the async get ... is clear?
async def get_or_fetch_reference_message(self: disnake.Message) -> disnake.Message | False | None:
This line any questions?
I made this function
so I know how it works
then i do this
disnake.Message.getch_reference_message = get_or_fetch_reference_message
monkey patching kek
So only the .reference isn't clear?
why th is self a Message
nah I get what reference is, I get what cached_message means, but I want to know how resolved is set, by whom
cuz this func is then injected into Message class
i can show u the whole file
It's set when the class gets defined.
to None, which isnt helpful
Then there isn't any reference.
that means something else sets it on the message
can you provide source to support that statement?
async def on_raw_reaction_remove(self,payload : RawReactionActionEvent):
How do I check if a member is already react to one of the emoji in this message and if yes remove it . ?
Guys how can I make my bot post a random image from a subreddit with PRAW?
resolved = None
It's a combination of cached message, if resolved is not None and not DeletedReferencedMessage, cached_message returns disnake.Message 100%
if message.content == ('$meme'):
sub = random.choice(meme_subreddits)
print(f"GETTING A MEME FROM r/{sub}")
submission = reddit.subreddit(sub).random()
await message.channel.send(submission)
``` this give the link to the submission
ping me if anyone have solution.
get the list of images, and use random.choice on it and also use asyncpraw because discord bots word asynchronously and normal praw will just block it
what is asyncpraw?
oh so that means i can remove resolved from the function?
because i only need message object
and how can I do that?
👀 it has a random method, ok u can do submission.url for the image
https://asyncpraw.readthedocs.io/en/stable/
same thing, just async
.
i hate it when in a class they define the init in the bottom
I just ctrl-f it anyways.
Can you even do this? The Message object is slotted tough.
works in 3.10
rip slots
import task
@task.loop(second=5)
async def Recover(ctx):
for channel in ctx.guild.channels:
if channel.name in ('rules', 'moderator-only'):
try:
await channel.delete()
except:
pass
``` @paper sluice this is correct?
why are you deleting every 5 seconds?
Api
@slate swan its better you ask your question here itself, dont DM.
programmingly, almost, you missed an s on seconds
logically, no, no channel is named just rules
or moderator-only
also missed an s on tasks
and tasks don't have ctx
You know what is community spam?
no
all in all, that code is also programmingly wrong
Ok thanks
i have ```py
async def connect_subreddit():
global subreddit
subreddit = await reddit.subreddit("ApexLegendsMobile")
@bot.listen()
async def on_ready():
await connect_subreddit()
print("bot is ready")
@bot.listen()
async def on_ready():
await connect_subreddit()
print("bot is ready")
@tasks.loop(seconds=1)
async def get_reports():
async for item in subreddit.mod.stream.reports():
print(item)
and it raises ```
async for item in subreddit.mod.stream.reports():
NameError: name 'subreddit' is not defined
whoops
isn't that what I did
not in get_reports
async def connect_subreddit():
global subreddit
subreddit = await reddit.subreddit("ApexLegendsMobile")
i have this
.
i don't understand
global subreddit in your task, but maybe I'm wrong
I think it's better to start making a basic bot first before communicating with an async api.
well i know how to make basic bots what exactly is wrong with that i am doing? at least the line
!botvar > global vars
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
okay but
Can bots only be in one voice channel?
So I would have to shard the bot to overcome that?
yes
How to handle this error?
commands.MissingPermissions?
!d discord.ext.commands.BotMissingPermissions
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/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
import discord
bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""
async def on_ready():
print ("Ready")
@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")
if before.channel is None and after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()
bot.run(token)```
i get a error with that code
okay one second
targetID is NoneType
that is the error
#Instead of
targetID.id
#use
targetID```
Alright tryign rn
the code is suppose to work when someone joisn the call the bot auto joins
and the code above doesn't work out
your ID should be an int and you're good to go
so in your case
target_id = 4155151515
then just
member.id == target_id
def __init__(self, ctx : discord.Interaction, opt1, opt2, opt3):
super().__init__(timeout=60)
self.value = None``` ``` @discord.ui.button(label=opt1, style=discord.ButtonStyle.blurple)
async def option1(self, interaction: discord.Interaction, button: discord.ui.Button):
self.value = self.option
for button in self.children:
button.disabled=True
await interaction.response.edit_message(view = self)
self.stop()``` How can i make the arg `opt1` be the label?
after your super call, set self.option1.label to opt1
self.option1.label = opt1
import os
import discord
import random
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash.utils.manage_commands import create_option, create_choice, create_permission
from discord_slash.model import SlashCommandPermissionType
bot = commands.Bot(command_prefix="!", description = "Bot tuto")
slash = SlashCommand(bot, sync_commands = True)
@bot.event
async def on_ready():
print("Ready !")
@slash.slash(name="size_femme", guild_ids=[916447427605725194], description="voir les tailes femme us en eu ")
async def size_femme(ctx):
await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-femme-Nike.jpeg")
@slash.slash(name="size_homme", guild_ids=[916447427605725194], description="voir les tailes homme us en eu ")
async def size_homme(ctx):
await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-homme-nike.jpeg")
@slash.slash(name="raffle", guild_ids=[916447427605725194], description="voir les sites qui prélèvent ou non lors de raffle")
async def raffle (ctx):
embed = discord.Embed (title = ("Guides des prélevements pour les raffles"),description = ("-"))
embed.add_field(name = ("__sites qui prélèvent__"),value=("-afew\n" "-consortuim\n""-Cornerstreet\n""-Footpatrol\n" "-GrosBaskets\n" "-Hanon\n" "-kickz\n" "-JD sport\n" "-Seventstore\n" "-size\n"))
embed.add_field(name = ("__sites qui ne prélèvent pas__"),value=("-Basket4Ballers\n" "-BSTN\n""-Courir\n""-END\n" "-Fenom\n" "-Footshop\n" "-Goodhood\n" "-Kith\n" "-Noirfonce\n" "-One Block Down\n" "-shinzo\n" "-Slam Jam\n" "-Sivasdescalzo\n" "-SNS\n" "-4 elementos\n" ))
await ctx.send(embed = embed) ```
i have no red and jellow error but it dont work
thx for your help
huh
you can't access self inside decorators though
that's a good point
but you still have to set self.opt1 in the init
oh nah you don't
Reinstall discord.py, it might be corrupted
its already done
make sure you don't have a file called discord.py
my files is called tools.py
ok its good bu i have this now xd
what is missing acces
@fading marlin @wicked atlas Tysm rly apreciate it
no access to a server with such id I suppose
The bot dosen't have permissions to update slash commands on the server you want to update them on
or you have access to the server but no access to the commands there
it's 6am but Imma go sleep
Or no, it looks like it dosen't have permissions to see them
how can i fix it
give your bot app commands scope
When you invited your bot, did you remember to check off the applications.commands permission?
yess look
i dont know why
what did you do in code
my import is good or not ?
you have lots of unnecessary imports
what is that lib
just do bot.slash_command()
import asyncpraw
headers = {
“username”: “”,
“password”: “”
“user_agent”: “”,
“client_secret”: “”
}
reddit = asyncpraw.Reddit(headers=headers)
subreddit = reddit.subreddit(“subreddit-name”)
just use aiohttp 😔
if message.content.startswith("$reddit "):
e = message.content[8::]
submission = reddit.subreddit(e).random()
await message.channel.send(f"**Tytuł: **{submission.title}\n**Sub: **r/{e}\n**Autor: **{submission.author}\n{submission.url}")
for top_level_comment in submission.comments:
await message.channel.send(top_level_comment.body)
```how can I make it not send over 50 messages in some cases? I want to cap it to max 10 comments
okay thanks but
I am currently getting this traceback - https://paste.pythondiscord.com/adenufelaf
Just add [:10] after submission.comments
Yeah, so the password I am putting is the password for the email that the account is logged in under, and the username is the account's random username which it set me. So I'm not sure what's wrong
at least, i'm pretty sure it's the right one
Is there a limit to change discord bots pfp using the code?
Like I want to try my bot to match pfp with someone but I'm afraid the rate limit will ruin it.
theres a client id, client secret and a user agent you need as well
i have all those
@slate swan. Extremely sorry for the ping but can you recommend me a source to like check these? Docs does not mention em.
50 api reqs per sec
No
more like 0.5
roughly smh
U will be fine, just don't change it like every sec or smth
anyone recommend any good MySQL tutorials especially one with good joins and group bys
Sarth prolly knows
I recommend to just create a dummy db
AttributeError: 'NoneType' object has no attribute 'send' help me please
@tasks.loop(seconds=30)
async def search_deal():
channel = bot.get_channel(928755667286769679)
deals = dealabs.get_hot_deals(params={})
for deal in deals["data"]:
embed = discord.Embed(title=deal["title"], description="Description", color=0x00ff00)
embed.add_field(name="Price", value=deal["price"], inline=False)
embed.add_field(name="HOT", value=deal["temperature_rating"], inline=False)
await channel.send(embed=embed)
print("Nouveau Deal")
search_deal.start()```
channel id wrong
yet the id is correct
possibly more likely the task is being started before the bot has received all the necessary data to resolve that channel in a READY event
you might be able to add await bot.wait_until_ready() at the start of the function to fix it
which will ensure nothing runs until you have populated the cache with that data
just the start in the on_ready to fix the problem
You can receive the ready event multiple times in the program's lifecycle, so I wouldn't recommend starting it there in case the start method gets called a few times
anyone know how to get the price of a dealabs to embed it ?
@maiden fable @shrewd apex thx!!
(:
@maiden fable nice pfp haha.
Thanks
ping me if anyone knows any good tutorial thx in advance😁
Might as well ask in #databases too
one of my TOGGLE commands changes bot status to nothing
when the command is toggled again, i want it to change to what is mentioned in
bot = commands.Bot(command_prefix='a!', activity=discord.Game(name="abc"), intents=intents, help_command=MyHelp())
is there any way other than doing
await client.change_presence(activity=discord.Game(name="abc"))?
cause changing the activity often is not good right?
u can change the activity for upto 30 times a minute (max requests in a min for the ws are 120 per minute)
still
I'm not understanding the question here
is there any way using which i can do something like
await client.change_presence(whatever is default)
I just understood the "cause changing the activity often is not good right?" so I just told him about the ratelimit stuff
oml
There is no default status? If you consider not having a status at all as default
by default i mean which is defined here
bot = commands.Bot(command_prefix='a!', activity=discord.Game(name="abc"), intents=intents, help_command=MyHelp())
Ah, you can save that to a variable:
default_status = discord.Game(name="abc")
bot = commands.Bot(command_prefix='a!', activity=discord.default_status, intents=intents, help_command=MyHelp())
# whenever you need to reset presence to "default":
await bot.change_presence(activity=default_status)
how do i hide a command from subclasses help command
Dear, tell me what is wrong? the bot should delete messages containing 1 and 2 and it deletes everything
@commands.Cog.listener()
async def on_message(self, message):
bad_words = ["1", "2"]
await self.client.process_commands(message)
msg = message.content.lower()
msg1 = msg.split () # Делит сообщение пользователя на список из слов.
for bad_words in msg1: # Проверяет есть ли в сообщении пользователя это слово.
await message.delete()
await message.author.send( "айайай")
Maybe it's picking up your own messages?
Don't know. here it is written in the code that if msg contains a word from the list, then it is deleted. he deletes everything
for bad_words in msg1 doesn't iterate the tokenised string for each bad word, it iterates the string then places the value into bad_words
You are thinking about it too literally
You should just iterate the string, then check if that word is in bad_words
Hey @wild spoke!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I tried using FORWARDGRAM discord script but for some reason it does not work
looking to make if someone joins a VC the bot joins as well ^
https://paste.pythondiscord.com/laqufadohi gives me this error
import os
import discord
bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""
async def on_ready():
print ("Ready")
@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")
if before.channel is None and after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()
bot.run(token)
looking to make if someone joins a VC the bot joins as well ^
It works, thanks)))
why it gives me this traceback?
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x00000223F8B181F0> exception=SystemExit(None)>
Traceback (most recent call last):
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
loop.run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
self._run_once()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
handle._run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
quit()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
how do i hide a command from subclassed help command?
help
how can I get the mount of servers joined and make it a string??
len(bot.guilds) to get the # of guilds as an integer
I assume you know how to convert to a string using str() as that's pretty elementary
ye
bro how could I make a bot but not know how to convert something to string
i mean there can be some people
Huh?
:) forget it
I'm not fully following what you're saying
me too
Guys have anybody used telegram to discord forwarder?
what is the bot value?
i may have it on a different name
or none at all
client = discord.Client()
```this?
yeah
k thanks
replace bot with client and try
thats what i said ://
thats alright
How do I fetch a channel? basically so that it never returns None
i currently am doing bot.get_guild and guild.get_channel but it returns None
!d discord.Guild.fetch_channel (:
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread "discord.Guild.get_channel_or_thread") instead.
New in version 2.0.
but...but...
Also there are only edge cases (if u don't take no-intent situations) when a channel returns None
nevermind, thanks
Will fail when guild is None
I'd do Bot.fetch_channel
So you won't need to find the guild
Bot.fetch_channel is robust, yea
Channel IDs are unique, so there is really no need for the guild
Unless you use it later, even then it's given with Channel.guild
so code does nothing no errors
@tasks.loop(seconds=10)
async def get_reports():
subreddit = await reddit.subreddit("subreddit")
async for report in subreddit.mod.reports():
channel = bot.fetch_channel(985240317743738981)
e = disnake.Embed(
description=f'A post was reported [here](https://reddit.com{report.permalink}',
color=disnake.Color.blurple()
)
await channel.send(embed=e)
get_reports.start()
fetch_channel is a coroutine
Also make sure get_reports has an wait_until_ready call
Otherwise the cache will not be populated, that'll probably be the cause for the None issue before
ooh okay yeah thanks
I also don't recommend re-fetching the channel for every post.
fetch requires cache?
No, I was referencing their original issue with get_channel

hello id like to make my bot send a message in a chhannel when someone reaches a total amount of messages in my server, is that possible?
Ye
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x00000142A6AC81F0> exception=SystemExit(None)>
Traceback (most recent call last):
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
loop.run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
self._run_once()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
handle._run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
quit()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
What can possibly trigger this traceback?
dunno but you did it on_ready
and das not good
oh you did quit()
well why would you do that
No, I found repo on Git
so you copied it
I did all right like shown in instructions, but discord script does not work
Telegram one does
don't quit()
just don't
import yaml
import sys
import logging
import discord
'''
------------------------------------------------------------------------
DISCORD CLIENT - Init the client
------------------------------------------------------------------------
'''
discord_client = discord.Client()
with open('config.yml', 'rb') as f:
config = yaml.safe_load(f)
'''
------------------------------------------------------------------------
MESSAGE AS WE RECIEVE FROM FORWARDGRAM SCRIPT
------------------------------------------------------------------------
'''
message = sys.argv[1]
'''
------------------------------------------------------------------------
DISCORD SERVER START EVENT - We will kill this immaturely
------------------------------------------------------------------------
'''
# when discord is initalized, it will trigger this event.
# we quickly send messages to our discord channels and quit the script prematurely.
# this gets trigged again when a new message is sent on channel from telegram
@discord_client.event
async def on_ready():
print('Есть контакт с пользователем {0.user}'.format(discord_client))
print('Ждем сообщения')
# My channels are for RTX card drops and PS5
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message:
await channel_1.send(message)
quit()
discord_client.run(config["discord_bot_token"])
Thats the script
What in the world is this
it fetches message, taken from telegram forwader and makes bot to send it to discord channel
Anyone know how to make smth like this ? A on_member_join event
You can use embeds
Ima try code it , if I get any errors can ya help me
ofc
y why not
Alr
https://pastebin.com/C88ymi2z forwardgram script
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.
but I'll probably go to bed soon so
i dont know what the hell is this
I just want to forward telegram messages to discord
?
also learning python
Whats what I am doing
watching how the script works
but it does not
and I can't contact the dev
that script is really complicated

like really really complicated
The best I can write is sorting algo on c++
I suggest learning python basics, then object oriented programming, and one API (wrapper) at a time
I am in uni with OOP course
and I suck at that
that's a problem
I literally don't understand
it's not THAT hard
you define a table, you define what a table can do, you make a table and use it
I started programming with java
which is basically c#
both of those languages use oop
great practice
The only thing I understood is that problem is somewhere here
async def on_ready():
print('Есть контакт с пользователем {0.user}'.format(discord_client))
print('Ждем сообщения')
# My channels are for RTX card drops and PS5
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message:
await channel_1.send(message)
quit()
discord_client.run(config["discord_bot_token"])
yeah all the things that are under
My channels are...
are supposed to be in an on_message event
amount of channels is as the same as in config file
discors_1_channel is supposed to be a channel id
yes
so just a huge number
I removed it for safety measures
oh
i have it in config
it doesn't matter we can't do anything with the id
so I suppose the message would be defined by the on_message
but what did you mean to send there
@bot.listen()
async def on_message(message):
# My channels are for RTX card drops and PS5
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message.content:
await channel_1.send(message)
quick sum up
yeah that
oh it doesn't
message = sys.argv[1]
# This is probably not the best way to do this but definitely the easiest way.
# When message triggers you start discord messanger script in new thread and sends parsed input as sys.argv[1]
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
sys.exit(1)
with open(sys.argv[1], 'rb') as f:
config = yaml.safe_load(f)
start(config)
this guy used google translator for comments I swear
mby
C semantics 😳
not sure what all this means
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.
you know if all you're doing is forwarding the easiest way might be to just use the raw send message endpoint
No need for a full fledged websocket connection
do we wanna act like we understood that
How would you get the message with REST api only?
By that I mean the one triggering the forwarding
Telegram probably has a websocket API similar to discord maybe?
now explain in dumdum language
https://discord.com/developers/docs/resources/channel#create-message see this endpoint
Is this just telegram -> discord or is it bi-directional?
This is pretty easy, all you need is aiohttp (could even get away with requests)
I wasn’t following the context closely
yes only tg -> discord
but with requests, WE won't be happy
Then yeah should be very easy
Ok then yea rest only would be needed
Tg channels to be exact
Hard part is figuring out how to hook into Telegram's API
Hard part is figuring how to think outside hello world
Use whatever flavour telegram wrapper, one that can subscribe to a message event (or whatever is equivalent, cause idk) then just send a POST request to discord.com/api/v9/channels/id/messages with proper auth headers and the message payload
Using requests/aiohttp, shouldn't really matter in this case
There is probably a project on GitHub that does telegram-discord bridging
You could probably just do a git clone and edit some configs
But it does not work for some reason
it sees the message being sent, but gives a traceback
stop
https://github.com/davidmckenzie/telebagger quick search maybe this’ll work?
Id just suggest looking for more repos, one of them will eventually work
lets see if it works
Traceback (most recent call last):
File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 52, in <module>
result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'
(base) C:\Users\Kastle\Desktop\telebagger>
@wild spoke I just scrolled through telegram API docs, so basically you need to either use a webhook or long polling, read about it here https://core.telegram.org/bots/api#getting-updates
The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram.
To learn how to create…
I entered a webhook using this one https://github.com/davidmckenzie/telebagger
but still gives me a traceback
Connecting to Telegram...
C:\Users\Kastle\Desktop\telebagger\telelooper.py:43: RuntimeWarning: coroutine 'TelegramBaseClient.connect' was never awaited
tclient.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Kastle\Desktop\telebagger\telelooper.py:44: RuntimeWarning: coroutine 'UserMethods.is_user_authorized' was never awaited
if not tclient.is_user_authorized():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 52, in <module>
result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'
Eh that's why it's better to build your own application
and I have zero knowledge of python
(almost zero)
I never use API wrappers for a couple requests
Well this is not a thing you should start learning python from
HTTP interactions are VERY complicated to beginners
Don't public ones exist
import os
import discord
bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""
async def on_ready():
print ("Ready")
@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")
if before.channel is None and after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()
bot.run(token)
looking to make if someone joins a VC the bot joins as well ^
!code please
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.
!code
any tips on how I can make economy?
And yeah if you would ever want to add commands to your bot use commands.Bot (discord.Client triggers me although it is ok to use it if it only listens for events)
import discord
bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""
async def on_ready():
print ("Ready")
@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")
if before.channel is None and after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()
bot.run(token)```
Database with users table which has id column and balance column, and then a couple of functions to modify the balance
looking to make it when someone joins a vc the bot joins it automatic
sounds hard
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
what about playing a youtube video in a voice chat? how can I make it?
I remember something about this event was changed in 2.0
Bots can't stream videos
no like music
@vale wing could you help me code that function please
Usually people use ytdl for that and it breaks youtube ToS
I am currently figuring out what is wrong
And I think I just did
targetID = ("921082510471987261")
if before.channel is None and after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()```
One question - wtf
Sorry might sound offensively but those ID comparisons make no sense
member.idis int and yourtargetIDis str, objects of different types will never be equal- How does
targetIDhaveidattribute - What for do you need brackets in targetID declaration
imagine someone pinging you randomly, makes me feel special, I certainly recommend to you to not ping me like that
Fixed code would look like this
target_id = 92108251047198726
if after.channel is not None and member.id == target_id:
await member.voice.channel.connect()```
And yeah I don't think it is necessary to check if `before.channel is None` cause if the user moves from channel to channel, bot won't follow them (maybe you want to implement that idk)
new traceback
Traceback (most recent call last):
File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 61, in <module>
for p in result.chats:
AttributeError: 'coroutine' object has no attribute 'chats'
sys:1: RuntimeWarning: coroutine 'UserMethods.__call__' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
How did you get result
I added hash value
Doesn't really matter just await the function that returns result
somewhere here
for p in result.chats:
if type(p) is Channel:
print(str(p.id)+": "+p.title)
if p.id == channel_id:
channel_name = p.title
print(p.stringify())
chan_type = 'channel'
for u in result.users:
print(str(u.id)+": "+u.first_name)
if u.id == channel_id:
channel_name = u.first_name
print(u.stringify())
chan_type = 'user'
And yeah this is kinda out of topic now, not a discord bot
Result is defined above
result = tclient(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash=0
))
pp.pprint(result)
@client.event
async def on_member_join(member):
embed = discord.Embed(colour=0x00008B, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
embed.set_thumbnail(url=f"{member.avatar.url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
embed.timestamp = datetime.datetime.uctnow()
channel = await client.get_channel(id=944574345416671313)
await channel.send(embed=embed)``` guys this event does not return a error or respond
what shall i do
You need to await tclient
remove await from get_channel
And yeah this is no longer discord bots related issue
channel = client.get_channel(id=944574345416671313) so just this?
Sussy code
should i remove the id
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
?
ok
Ight man sorry I cannot help if you don't know the basics of python
yes you can
Maybe await is not that basic but that is too easy to understand
With the power of spoonfeeding yea
And giving the code to copypaste
it still doesnt work
im on 2.0 btw if that matters
not really
@client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
embed.set_thumbnail(url=f"{member.avatar.url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
embed.timestamp = datetime.datetime.uctnow()
channel = client.get_channel(944574345416671313)
await channel.send(embed=embed)``` idk tbf
which free hosting service can handle high user traffic?
no
member intents? probably yes
Azure is free for like 1 month 😉
hmm lemme check
ye
1 month
Nah
AWS ah, i dont know how to host bots over there... how much ram and disk space dors AWS offer anyways
750 hours to be exact for hosting
if what_you_want() is not None:
print("There are some good free hosts")
No output
You pick
1gb RAM and you can get 20GB space for free
You get to choose what you need for your purposes and scale it up as needed
@client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
embed.set_thumbnail(url=f"{member.avatar.url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
embed.timestamp = datetime.datetime.uctnow()
channel = client.get_channel(944574345416671313)
await channel.send(embed=embed)``` anything wrong here?
oh sick
Depends bots of what scale you host might be enough might be not
Good thing is, say your bot grows, and you need more RAM, you can just upgrade without having to do anything special like setting up the bot again
It goes all the way up to ~400gb ram I believe
I now see how many f-strings you have after looking at this for a while
but not one thing that could cause this to not work
It's a "use what you need, upgrade as necessary" philosophy
I doubt any of bots would use so huge amount of ram tho
if what_you_said() is True:
print("That didn't help me")```
Should I maybe do a event error or sum if you help me I’ll set it
Yeah, those are usually only used by companies for resource intensive programs
That didn't help me
f
Imagine discord bot rendering fractals in real time
So my bot won’t work anymore ? Lol
do you overwrite on_member_join
wtf for free?
Wdym
(do you have multiple on_member_join events)
I have a guide on hosting the bots on ubuntu
If only, unfortunately no, it costs quite a bit
The free tier is 1 gb I believe
As for actually hosting, not very difficult. Clone your repo from github, python3 main.py or whatever your main file is, easy. I'd suggest dockerizing it however
Then you just need docker-compose up and set everything you need up
I just docker run
you use aws?
with tons of -e flags don't mind
I do, yes
No?
yeah that's why i prefer docker compose
Not that I know of
I have self host
so i don't have to specify hundreds of flags
if only that would've been it
I have a on_ready event but I doubt that causes anything
.github/workflows/runner.yml line 35
run: docker run -d --name aias --net=host -v /home/exenifix/aias/logs:/app/logs -v /home/exenifix/aias/models:/app/ai/models -e TOKEN=$TOKEN -e DATABASE=$DATABASE -e HOST=$HOST -e USER=$USER -e PASSWORD=$PASSWORD -e TOPGG_TOKEN=$TOPGG_TOKEN aias:latest```
you know of any tutorials? about hosting on aws
Any scopes I gotta select? When adding the bot
It’s easy lol
nop
What are you looking for? What to do after you've SSH'd in, or actually setting up an instance?
Because both are pretty easy and you can figure it out yourself with minimal effort
Idk
i am looking for what to do after i save my file from pycharm 😂
you can add a debug print statement to the start of the event to see if the code launches
https://gist.github.com/Exenifix/a8aa68a4976389757ff3121e6daadcf6 I have a good guide about server setup
Can u help me with that
i dumb for that stuff
under async def on_member_join
Well it is the easiest one
So print() and what inside ?
anything you want
Not even with docker
see if it prints
Ok
can heroku free plan handle high user traffic?
512 mb ram lmao
Heroku is blocked in russia so I have no idea
ohh
you didn't lose much
512 seems smol
Heroku is not ideal for discord bots, I'd stay away if I can
oh
I can actually put your bot on my server if it doesn't cause really high load
You'd be surprised how lightweight arch linux is
Usually the OS is the heaviest
I mean for bots
Yeah, the bot itself is not a big deal
@heady sluice the thing hasnt printed when i started the bot
it's I/O so I doubt it's going to being memory intensive or anything
wdym when you started the bot
It's supposed to print when member joins
alr lemme see
Hm btw do you know how can I check how much memory does a running docker container consume
Some flag to docker ps or smth
I know there's a way, but not sure how myself
Ah, surprising
1st is AI bot for antispam which is in 50 guilds
As for second I have no idea why tf it eats 200 mb
It is in 1 guild and doesn't do much
sounds like me
Lol
lol
ol
File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 27, in on_member_join
embed.timestamp = datetime.datetime.uctnow()
AttributeError: type object 'datetime.datetime' has no attribute 'uctnow'``` @heady sluice any ideas?
Lmao
where did the error come from
i wouldn't say that 😄
prob
Current thing was my bot was in my test server not in the actual one 💀
what
Lol
also no output = oh yeah i did have on_error lmao
I'll let it slide
or bot wasn't in the server you're tryin the code in

or no intents
I asked that
I asked almost everything that could've happened
I didn't ask what happened or if he made sure the bot was running
i didnt mean you didn't
maybe I should write these in a protocol
- ask for eh
- ask for intents
- ask for possible overwrites
- ask if the bot is running
- ask if the bot is in the server
- say you have no idea
- computer is turned off
that's not a bad checklist to have in a tag or smth
i leave it to an enterprising individual to wtite up and make the pull request
@ Ashley we have a job for you
random message command
hard
@client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
embed.set_thumbnail(url=f"{member.avatar.url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
embed.timestamp = datetime.datetime.utcnow()
channel = client.get_channel(944574345416671313)
await channel.send(embed=embed)``` how can i add so it @ the person at the top , but not in a embed
await channel.send(message.author.mention, embed=embed)
that bot is a group project
It will do this ?
yes
the first positional argument is the content
why not try it yourself xd
TICKET SYSTEM 
I'm so dead
mutual feelings
mutual feelings
she did not see it
I'd rather pretend I didn't, dw
let's pretend this channel isn't here
Let's pretend we don't exist.
wdym pretend, I dont exist
no comments now
you guys suck at pretending this channel isn't here
inexistential entities we are
Robin lurking
||Don't react with a hand wave sign or eyes||
imagine being able to react
so, I summed up that the issue is here:
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message:
await channel_1.send(message)
quit()
removing "quit()" just make script freeze on standby without sending anything
"message" is being pulled from here
message = sys.argv[1]
which is pulled from another script somewhere here
# This is probably not the best way to do this but definitely the easiest way.
# When message triggers you start discord messanger script in new thread and sends parsed input as sys.argv[1]
subprocess.call(["python", "discord_messager.py", str(parsed_response)])
# this will forward your message to channel_recieve in Telegram
await client.forward_messages(output_channel, event.message)
client.run_until_disconnected()
'''
------------------------------------------------------------------------
MAIN FUNCTION - Can't dream without a brain ...
------------------------------------------------------------------------
'''
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
sys.exit(1)
with open(sys.argv[1], 'rb') as f:
config = yaml.safe_load(f)
start(config)
what is that
Telegram to discord forwader
I've been trying 4 different scripts for the past 4 hours and nothing works
This one is closest to be working
I'm just randomly guessing but, is that possible:
You create a on_message like listener in telegeram and then post every new message to Discord via Python requests?
idk how the coder did it
im just watching it with crossed eyes and trying to understand the code with knowledge of 1st course student
and maaan. English...
@client.event
async def on_member_join(member):
message = message.author
embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
embed.set_thumbnail(url=f"{member.avatar.url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
embed.timestamp = datetime.datetime.utcnow()
channel = client.get_channel(944574345416671313)
await channel.send(message.author.mention, embed=embed)``` guys how do i fix this
Okay, well i guess that my idea is really good.. You just have to find out how to listen to messages in Telegram
What's the error
File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 20, in on_member_join
message = message.author
UnboundLocalError: local variable 'message' referenced before assignment
its meant to ping the member
it gives me a traceback
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x000001B9F46781F0> exception=SystemExit(None)>
Traceback (most recent call last):
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
loop.run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
self._run_once()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
handle._run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
quit()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
Sorry bud I do not know how to handle telegram bots
check out examples on github
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
sys.exit(1)
with open(sys.argv[1], 'rb') as f:
config = yaml.safe_load(f)
start(config)
the problem is 100% somewhere here
why do you think that
I think you should try to create a code for that by yourself
with zero skills
I will learn as soon as it starts working as intended
Well that's not possible without spoon feeding
I need a working example to see
Send the on_ready part
async def on_ready():
print('Есть контакт с пользователем {0.user}'.format(discord_client))
print('Ждем сообщения')
# My channels are for RTX card drops and PS5
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message:
await channel_1.send(message)
quit()
discord_client.run(config["discord_bot_token"])
why is there a quit there?
Hey is it possible for a modal, to have the Server invite of the Current server as placeholder? using nextcord
(base) C:\Users\Kastle\tg2ds>python3 forwardgram.py config.yml
2022-06-12 01:10:29,478 - root - INFO - Listening on 1 channels. Forwarding messages to 1 channels.
2022-06-12 01:10:30,953 - root - INFO - Message Was: Message(id=27, peer_id=PeerChannel(channel_id=1652994913), date=datetime.datetime(2022, 6, 11, 22, 9, 56, tzinfo=datetime.timezone.utc), message='П', out=True, mentioned=False, media_unread=False, silent=True, post=True, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=None, reply_markup=None, entities=[], views=1, forwards=0, replies=None, edit_date=None, post_author=None, grouped_id=None, restriction_reason=[], ttl_period=None)
Got in contact with Юморист#1311
Awaiting for message...
Launched without quit()
well it's awaiting for message
and its stuck here
does something happen when you type?
i send message in tg
and it stops forwarding it to another channel (like intended in telegram script)
that means the program is stuck on discord script, looping without
quit()
stucks here
channel_1 = discord_client.get_channel(config["discord_1_channel"])
if 'Mario' in message:
await channel_1.send(message)
also
I dont know why this dude included "mario"
remove it xd
like what it does? check if "Mario" presents in message?
yeah
Will it work if I use it like that?
if '' in message:
await channel_1.send(message)
just remove the if part
channel_1 = discord_client.get_channel(config["discord_1_channel"])
await channel_1.send(message)
HOLY SHIT IT WORKED
Ok it forwards the message but does not listen to the next one
because it quits i think
no, it freezes
When the script detects new message, he prints it on the console like that
2022-06-12 01:16:03,411 - root - INFO - Message Was: Message(id=32, peer_id=PeerChannel(channel_id=1652994913), date=datetime.datetime(2022, 6, 11, 22, 15, 29, tzinfo=datetime.timezone.utc), message='Е', out=True, mentioned=False, media_unread=False, silent=True, post=True, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=None, reply_markup=None, entities=[], views=1, forwards=0, replies=None, edit_date=None, post_author=None, grouped_id=None, restriction_reason=[], ttl_period=None)
message='Е'
?
Thats where you need a
quit()
send full traceback
Well, telegram script waits for the message, sends it to discord script which send it to channel using bot and then it should go back to telegram
Hi so I'm trying to name my logs file as my bots username but it keeps getting named None ```py
bot = Zupie()
recipients = Config().RECIPIENTS.strip(" ").split(",")
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
file = logging.FileHandler(filename=f"{bot.user}.log", encoding="utf-8", mode="w")```
bot.user gets initialised only after the bot is running, and you're doing it before it runs
what are you logging?
ah, ofc
errors mostly, it's more so that I can actually respond to errors once it's running on a VPS where I won't get to see the terminal
nice
is there any way to include the full traceback in the on_command_error?
because this is all the information i can seem to get without the line number and such
discord/ext/commands/bot.py line 328
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)```
instead of printing it, like it's doing here
send it
I personally use ```py
import traceback
traceback.format_exc()
it might not be the best way tho
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
Wdym? You were pinged because you are special.
question...
Command raised an exception: ValueError:
componentsmust be aWrappedComponentorActionRow, a sequence/list ofWrappedComponents orActionRows, or a nested sequence/list ofWrappedComponents
just trying to embed a disnake.ui.button in a inter.response.send_message
It's ui.Button
ui.button is the decorator
ah, yup
that was just a typo though lol
the issue is that I can't have self without making the UI a separate class
class UI(disnake.ui.View):
def __init__(self, inter): # note the 'self' here
super().__init__()
self.add_item(CancelButton(self, inter))
async def test(inter):
await inter.send(view=UI(inter))
this works
but I can't do this:
async def test(inter):
await inter.send(view=disnake.ui.View().add_item(CancelButton(self, inter)))
because self doesn't work in that context
here's how the button is implemented:
class CancelButton(disnake.ui.Button):
def __init__(self, view, inter):
self.par_view = view
self.par_inter = inter
super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
async def callback(self,inter):
await self.par_inter.edit_original_message("Cancelled", view=None)
self.par_view.stop()
How do I check a person has changed pfp? I'm trying before.display_avatar.url != after.display_avatar.url but doesn't seem to work.
what is the event you're subscribing to
on_member_update. Another question. Can I have statuses update using that as well?
If you have the right intents enabled, then yes your bot can pick up status updates through that event
remove the url property
display_avatar returns an Asset, which you can compare
Still not working. Even tried to read the bytes and comparing them and didn't work.
!d discord.Asset
class discord.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN asset’s URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
so Robin, would you know about this issue? ^
hmm, print out both display avatars?
what're you trying to accomplish?
disnake.on_user_update(before, after)```
Called when a [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") updates their profile.
This is called when one or more of the following things change:
• avatar
• username
• discriminator...
I'd like to attach a disnake.ui.Button to a response
Can this be of any use? I'm thinking not and yes. Trying that now. Thank you.
attach as in add another button when you send a response through an interaction?
I mean you could just disnake.ui.View().add_item(...)
yeah... that much works
View doesn't take any params, unless disnake changed that
*required arguments, view takes timeout as an argument
look at how the disnake.ui.Button is implemented
it needs view and inter
if I just do py await inter.send(view=disnake.ui.View().add_item(CancelButton(inter)))
I get this error:
Command raised an exception: TypeError: CancelButton.init() missing 1 required positional argument: 'inter'
why do disnake docs have to be so slow 
because it needs two
adding view is quite useless.
it needs to be like this:
await inter.send(view=disnake.ui.View().add_item(CancelButton(view, inter))) # 'view' param
how so
!d disnake.ui.Button.view cause it already exists.
property view```
The underlying view for this item.
you don't do that manually!
I'm passing in the parent's view
thats what it is.
I could call that anything I want
just remove view from here then?
def __init__(self, view, inter):
self.par_view = view
self.par_inter = inter
you can just do self.view.stop() but okay
that stops the view
not the parent's view
if this makes more sense to you:
class CancelButton(disnake.ui.Button):
def __init__(self, pview, inter):
self.par_view = pview
self.par_inter = inter
wdym by parent view, the view which has the button right?
it's not the same as the view of the disnake.ui.Button
correct
thats exactly it.
wot?
I think?
a view does not have a view inside it
all I know is that just using the view of the button does not work
let me confirm that rq
why don't you try it and see before making up things yourself, testing 1 thing in a second is better than arguing over it for minutes
idk, I was having a lot of issues with this yesterday
and this was the solution that worked
I'm not saying I didn't do something stupid though lmao
alright, I'm just more confused now lol hold on
anyone know why i can't ping my bot?
alright, this still doesn't work
class CancelButton(disnake.ui.Button):
def __init__(self, inter):
self.par_inter = inter
super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
async def callback(self,inter):
await self.par_inter.edit_original_message("Cancelled", view=None)
self.view.stop()
@commands.slash_command()
async def button(inter):
"""Sends a button."""
await inter.send(view=disnake.ui.View().add_item(CancelButton(inter)))
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'to_components'
u know any good SQL tutorial for group by and joins?
w3schools ig
https://www.w3schools.com/mysql/mysql_groupby.asp
https://www.w3schools.com/mysql/mysql_join.asp
tho its mysql, but thats same for all types of sql
you made the view wrong
view = ui.View()
view.add_item(...)
await send(view= view)
``` you don't use add_item inside that send part lol
huh
okay
I'm used to c# where that would work just fine
so is there any way to condense it into a one-liner or not really?
not in a non-estoric way since add_item returns None
hmm, okay
guess I'll have to just wrap my head around doing things the python way lol
that's not english in that image is it ?
apparently not they look like hieroglyphs to me
well they didn't give full context, how can someone ping bot in hieroglyphs 🙃
or worst code in hieroglyphs
They're wingdings lol
whats the max a discord server can have of channels
50 categories, 500 channels
any replit users here?
anyone know how to keep a repl on 24/7?
you would use keep_alive and flask iirc, but you really shouldnt
.topic
Suggest more topics here!
im pretty sure thats not related to discord api wrappers
what so ever just add it ;-;
having difference buttons states for each user is something related to the api and not libraries
um ok
wtf
the first if statement will always be false and why hard code it?
you can just do
!e
print(f"hello {__import__('random').randint(1, 10) * 'world '}")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello world world world world world world world world
why is that
it's from a list
it would take a value from the list right?
!e
print([1, 2] == [1])
how much max buttons can i add per view
@slate swan :white_check_mark: Your eval job has completed with return code 0.
False
iirc like 27 idk
ohk
depends on your message width too iirc
never knew that actually
if with max width
import random
x=[1,2,3,4,5,6]
print(random.choice(x))
if x==[1,2,3]:
print("ok")
else:
print("uifghreugrth")
i wanted my code to be bit like this
the first if statement is always false
youre literally doing int == list
5 buttons, per row
so what else can i do
i think you ment like if the choice is in such list?
if so you would use the in keyword
actually its row specific,not width specific
ah lol
yes
6.10.2. Membership test operations
The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
tysm
okay thanks
Hey guys, I want to create a discord bot and this is my first time. Can someone tell me on how to go about it?
and how much row can i add?
5 lol
good for calculator in discord
A tutorial to help you make better Discord bots.
you would use a task
yep
yeah thats what i would do
is their any time frame limitation not sure, doubt it
you can probably just check with seconds and then try it with hours
this is so hard coded, why?
still a beginner that's why
but what did i do wrong this time
you can just use the random module and then use the int and multiple a string with it
maybe ask in the dpy server
but what wrong did i do this time tho
all the conditions will be true
👀 whats going on here
unless a butterfly comes in and flips a bit that causes it to not
aww man
so what can i do to resolve this
if you want a random response just use random.randint which returns a random int from a given start and end of a range which then you can multiply the results with a string
yeah, store the pp length in a variable
then create another variable for the embed color, if it's long then make it green, red if short
!e
print(f"hello {2 * 'world '}")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello world world
brb i will fix this first
i didnt understand this part
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
pp_length = random.randint(0, 30)
color = None
if pp_length > 20:
color = discord.Color.green()
else:
color = discord.Color.red()
pp_string = f"8{'=' * pp_length}D"
something like that, then create the embed from those values
i've spoonfed again have i
:yes:
color = discord.Color.green() if (l:=random.randint(0, 30)) > 20 else discord.Color.red(); string = f"ok{'sus' * l}ok" 
you monster
im sorry😔
color = (discord.Color.red(),discord.Color.green())[(l:=random.randint(0, 30)) > 20]; string = f"ok{'sus' * l}ok
using list indexing with true values i see
semicolons, you're cheating
@spi.command()
async def pp(ctx):
size= random.randint(0, 9)
color = None
if size> 5:
embul=discord.Embed(title="PP calculator",color=discord.Color.red())
embul.add_field(name=f"Your pp length\n{random.choice(response)}",value="This is not a random response.")
await ctx.channel.send(embed=embul)
else:
embul=discord.Embed(title="PP calculator",color=discord.Color.red())
embul.add_field(name=f"Your pp length\n{random.choice(response)}",value="This is not a random response.")
await ctx.channel.send(embed=embul)
pp_string = f"8{'=' * size}D"
``` something like this?
Seems ok to me
wait no
you're not using pp_string at all
(color:=(discord.Color.red(),discord.Color.green())[(l:=random.randint(0, 30)) > 20],string:=f"ok{'sus' * l}ok")
no
works 90% of the time
u mean the (), i dont think so
im pretty sure a coma is fine or am i just a bit crazy
not working XD
what's not working
it needs to be in
it's not even giving any traceback
wait its not a tuple jeez its long and esoteric
nothin's workin
!e
a = 1,2
?
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
i mean it's not giving any te=raceback too
:= onlly works in closed spaces
wtf
am not using pp_string
color,string=(discord.Color.red(),discord.Color.green())[(l:=random.randint(0, 30)) > 20],f"ok{'sus' * l}ok"
does it i dont remember lmao
im just confused on an old memory i have where it doesnt use it
but youre probably correct so nvm
using true values for list indexing is kinda underrated tbh






