trying to send a an embed message based on event event - python

i'm trying to make a logger for deleted messages based on an event whenever the message is deleted
snipe_message_author = None
snipe_message_id = None
#client.event
async def on_message_delete(message):
global snipe_message_content
global snipe_message_author
global snipe_message_id
snipe_message_content = message.content
snipe_message_author = message.author.id
snipe_message_id = message.id
await asyncio.sleep(60)
if message.id == snipe_message_id:
snipe_message_author = None
snipe_message_content = None
snipe_message_id = None
#client.event
async def logs(ctx, message):
if snipe_message_content==None:
m == 1
else:
embed = discord.Embed(description=f"{snipe_message_content}")
embed.set_footer(text=f"Sniped by {message.author.name}#{message.author.discriminator}")
embed.set_author(name= f"<#{snipe_message_author}>")
await message.channel.send(client.get_channel('channel id'), embed=embed)
return
I'm encountering problems with this part....
#client.event
async def logs(ctx, message):
if snipe_message_content==None:
m == 1
else:
embed = discord.Embed(description=f"{snipe_message_content}")
embed.set_footer(text=f"Sniped by {message.author.name}#{message.author.discriminator}")
embed.set_author(name= f"<#{snipe_message_author}>")
await message.channel.send(client.get_channel('channnelid'), embed=embed)
return
I've tried using different methods but none have been working so far

You need a command?
#client.command()
async def logs(ctx):
global snipe_message_content
if snipe_message_content==None:
m = 1
else:
embed = discord.Embed(description=f"{snipe_message_content}")
embed.set_footer(text=f"Sniped by {ctx.author.name}#{ctx.author.discriminator}")
embed.set_author(name= f"<#{snipe_message_author}>")
await ctx.send(embed=embed)

Related

How do i make my discord bot reply to a certain user always with the same string?

made my own discord bot using py and trying to solve the issue in the title.
This is my current code for responses
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return ''
if p_message == 'alex':
return ''
if p_message == 'benji':
return ''
if message == 'roll':
return str(random.randint(1, 6))
if p_message == '!help':
return '`This is a help message that you can modify.`'
if p_message == '-':
return ''
if p_message == 'aja':
return ''
if p_message == 'christian':
return ''
This is where i call my responses. And execute the code from above
import discord
import responses
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
# #client.event
# async def on_message(message):
# if message.author.id == 195251214307426305:
# await message.channel.send("")
# #client.event
# async def on_message(message):
# if message.author.id == 305280287519145984:
# # Sending a message to the channel that the user is in.
# await message.channel.send("")
def run_discord_bot():
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running!')
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
TOKEN=""
with open("token.txt") as file:
TOKEN = file.read()
client.run(TOKEN)
Tried using msg.author.id and its unknown now. More then that i was sadly stunned by this issue and found no solutions online
I assume you use the discord libary, so this could be a solution to your problem
import discord #dependencies
client = discord.Client() #create a client object
#client.event #bind the function
async def on_message(message):
if message.author.id == 398238482382: #check for id
await message.channel.send("Hey") #send 'hey' to channel where the message was written
client.run(yout_token) #starts the bot

How to break a while loop using asyncio in discord python?

client = commands.Bot(command_prefix = '!')
stop_var = False
#client.event
async def on_ready():
print('Bot is ready.')
#client.command()
async def hello(ctx):
while (stop_var==False):
await asyncio.sleep(1)
await ctx.send('Hello!')
if stop_var:
break
#client.command()
async def stop(ctx):
await ctx.send('Stopped!')
stop_var = True
I'm trying to make it so when I type !stop, the !hello command loop ends, but my code does not work.
This seems to work:
#client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(msg: discord.Message):
return not msg.author.bot and msg.content.lower() == "!stop"
try:
if await client.wait_for("message", check=check, timeout=1.5):
await ctx.send("Stopped")
stop_var = True
except asyncio.TimeoutError:
print("no stop")
Also if you have overridden on_command_error event you can use this to avoid triggering it:
#client.command()
async def hello(ctx):
stop_var = False
while (not stop_var):
await asyncio.sleep(1)
await ctx.send('Hello!')
def check(ctx):
return not ctx.author.bot and ctx.command.name == "stop"
try:
if await client.wait_for("command", check=check, timeout=1.5):
stop_var = True
except asyncio.TimeoutError:
print("no stop")
#client.command()
async def stop(ctx):
await ctx.send("Stopped")

How to get member count at on_member_join event in discord.py

I am trying to get membercount at on_member_join event in discord.py
My code -
#bot.event
async def on_member_join(member):
await bot.get_channel(channel_id1).send(f"Welcome Message")
memberCount = 0
for member in member.guild.members:
if member.bot == False:
memberCount = memberCount + 1
await bot.get_channel(channel_id2).edit(name=f"Members: {memberCount}")
but the channel with channel_id2 is not updating and it becomes
Member: 0
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents=intents)
#bot.event
async def on_member_join(member):
guild = bot.get_guild(guild_id)
channel = bot.get_channel(channel_id)
mc = guild.member_count
await channel.send(f"{mc} members")
Actually i got something, but not sure about it.
can i create a new function to do that -
async def MemberCount(guild):
mc = 0
for member in guild:
if member.bot == False:
mc = mc + 1
return mc
#bot.event
async def on_member_join(member):
await bot.get_channel(channel_id1).send(f"Welcome Message")
memberCount = await MemberCount(message.guild)
await bot.get_channel(channel_id2).edit(name=f"Members: {memberCount}")

Other user can write -join and then bot will trigger the commend

So I'm making bot in python and I don't know how to make that other user can write -join and then bot will trigger the commend. My code currently is in cogs so I'm using #commands.command instead #bot.command. Here is my code:
class GamesCog(commands.Cog, name="Games"):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def game(self, ctx):
await ctx.send("Find a second person to play dice or play against the bot. (-join/-bot)")
await ctx.send(file=discord.File('game.jpg'))
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["-join", "-bot"]
msg = await self.bot.wait_for("message", check=check)
def setup(bot):
bot.add_cog(GamesCog(bot))
print('File games.py is ready')
I know that in the return msg.author author shouldn't be there, I just don't know what to replace it with.
You're actually doing nothing with the message, you're waiting for it, and then nothing
msg = await self.bot.wait_for("message", check=check)
if msg.content.lower() == "-join":
# Do something
elif msg.content.lower() == "-bot":
# Do something
def check(msg):
return msg.channel == ctx.channel and msg.content.lower() in ["-join", "-bot"]

Disconnect the music bot from voice channel

I have this as my music class to make my bot play music
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("localhost", 7000, 'server-utils', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
#commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if opt == "join":
print(f"music join command worked")
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
if opt == "play" and arg is not None:
try:
player = self.bot.music.player_manager.get(ctx.guild.id)
query = f'ytsearch:{arg}'
results = await player.node.get_tracks(query)
tracks = results['tracks'][0:10]
i = 0
query_result = ''
for track in tracks:
i = i + 1
query_result = query_result + f'{i}) {track["info"]["title"]}\n'
embed = discord.Embed()
embed.description = query_result
await ctx.channel.send(embed=embed)
def check(m):
return m.author.id == ctx.author.id
reponse = await self.bot.wait_for('message', check=check)
track = tracks[int(reponse.content)-1]
player.add(requester=ctx.author.id, track=track)
if not player.is_playing:
await player.play()
except Exception as error:
print(error)
if opt == "stop":
try:
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
except Exception as error:
print(error)
if opt == "leave":
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
await self.disconnect_from(ctx.guild.id)
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
Everythink works fine except the part to disconnect from the channel he is connected to... I've tried lots of things and can't figure out how to make it disconnect..
Ps: Here the command doesn't do anything but to print a list where I hoped there would be the bot connect, but it had nothing there
I believe it's because you're passing the guild id as opposed to the voice channels id, for example.
You're in the guild; Hello World with an ID of 12345
You're in the guilds voice channel of; Hello World voice channel which has an id of 6789.
so you're trying to use the guild.id as opposed to the voice channel id. Does this make sense?
Can't you do await ctx.voice_client.disconnect()
if opt == "leave":
player = self.bot.music.player_manager.get(ctx.guild.id)
if player.is_playing:
await player.stop()
await ctx.voice_client.disconnect()
I did a disconnect command on my Discord bot using VoiceClient.disconnect(). I got some trouble with it in my first approach because the connect command generated the VoiceClient object, but disconnect command could not use it since it was a local variable on the other command, so i just made it global and it works
#commands.command()
async def enter(self, ctx):
try:
canal = ctx.author.voice.channel
global voice_client
voice_client = await canal.connect()
except AttributeError:
await ctx.send("Você precisa estar conectado a um canal de voz")
except discord.errors.ClientException:
await ctx.send("Eu já estou conectado ao seu canal de voz")
#commands.command()
async def leave(self, ctx):
try:
await voice_client.disconnect()
except NameError:
await ctx.send("Eu não estou conectado a nenhum canal de voz :worried:")
The full music cog that I coded:
https://github.com/Voz-bonita/Discord-Bot/blob/master/Music%20extension.py

Categories