Using Adf.ly with Discord.py - discord.py

So I am using MurkAPI and had gotten help with this but I cannot seem to get it so when someone does $adfly and a url which is a adfly shortend link, the bot returns the link through the API and into the bot. This is the current code I have.
#commands.command(pass_context=True)
async def adfly(self, ctx):
async with aiohttp.ClientSession() as session:
await self.client.say(await fetch_adfly(session))
async def fetch_adfly(session):
async with session.get(adfly_url) as response:
return await response.text()
I have the MURKKEY working, however, I cannot get the URL part working.
adfly_url = 'https://murkapi.com/adfly.php?key={}&url={}'.format(MURKKEY)

If fetch_adfly is meant to handle transforming your url into an adfly url, you want the session in that function. Instead of passing a session, we want to pass the url that we want transformed. That might give us something like:
async def fetch_adfly(url):
async with aiohttp.ClientSession() as session:
adfly_url = 'https://murkapi.com/adfly.php?key={}&url={}'.format(MURKKEY, url)
async with session.get(adfly_url) as response:
return await response.text()
Then, you want to add a url parameter to your command and pass it to your function:
#commands.command(pass_context=True)
async def adfly(self, ctx, url):
await self.client.say(await fetch_adfly(url))
FWIW, I would suggest validating URLs.

Related

Can't figure out how to use discord.py ctx

I have tried to convert my discord bot's commands to using ctx instead of interactions but the code I have tried below does not work.
#bot.command(description="Says test")
async def test(ctx):
await ctx.send("Test")
My issue is that the command never loads.
Updated code but still broken
import discord
from discord import ui
from discord.ext import commands
bot = commands.Bot(command_prefix="/", intents = discord.Intents.all())
# Run code
#bot.event
async def on_ready():
print('The bot has sucuessfully logged in: {0.user}'.format(bot))
await bot.change_presence(activity=discord.Activity(type = discord.ActivityType.listening, name = f"Chilling Music - {len(bot.guilds)}"))
# Commands
#bot.command(description="Says Hello")
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}!")
#bot.command(description="Plays music")
async def play(ctx, song_name : str):
await ctx.author.voice.channel.connect()
await ctx.send(f"Now playing: {song_name}")
#bot.command(description="The amount of servers the bot is in")
async def servercount(ctx):
await ctx.send(f"Chill Bot is in {len(bot.guilds)} discord servers!")
#bot.command(description="The bots ping")
async def ping(ctx):
await ctx.send(f"🏓Pong\nChill Bot's ping is\n{round(bot.latency * 1000)} ms")
#bot.command(description="Announcement command")
async def announce(ctx, message : str):
await ctx.send(message)
#bot.command(description="Support Invite")
async def support(ctx):
await ctx.send(f"{ctx.author.mention} Please join our server for support! [invite]", ephemeral=True)
#bot.command(description = "Syncs up commands")
async def sync(ctx):
await ctx.send("Synced commands!", ephemeral=True)
bot.run('')
Your commands don't work because you incorrectly created an on_message event handler.
By overwriting it and not calling Bot.process_commands(), the library no longer tries to parse incoming messages into commands.
The docs also show this in the Frequently Asked Questions (https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working)
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message.
Also, don't auto-sync (you're doing it in on_ready). Make a message command and call it manually whenever you want to sync.

How do you add a reaction to the response of a slash command?

I'm facing problems trying to add a reaction to the bot's response when it responds to a slash command I entered.
#bot.slash_command(name='test', description="Test.")
async def test(ctx):
msg = await ctx.send("Hello.")
await msg.add_reaction('🤖')
As you can see it's supposed to add a reaction to it's own message.
But I get this error:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'PartialInteractionMessage' object has no attribute 'add_reaction'
Please tell me how do I add a reaction to a slash command.
Explanation
As per the error, ctx.send is returning a PartialInteractionMessage. From the docs:
This does not support most attributes and methods of nextcord.Message. The fetch() method can be used to retrieve the full InteractionMessage object.
Code
#bot.slash_command(name='test', description="Test.")
async def test(ctx):
msg = await ctx.send("Hello.")
full_msg = await msg.fetch()
await full_msg.add_reaction('🤖')

How do I make it so this message gets sent a specific channel? (Discord.py)

I want the message to get sent to a specific channel
async def on_message_edit(before, after):
await before.channel.send(
f'{before.author} edited a message.\n'
f'Before: {before.content}\n'
f'After: {after.content}'
)
To send a message in a specific channel you need first to fetch the choosed channel by using his id by using get_channel() like this:
specificChannel = bot.get_channel(int(YOUR_CHANNEL_ID_HERE))
Then your event block should look like this:
#client.event
async def on_message_edit(before, after):
specificChannel = bot.get_channel(int(YOUR_CHANNEL_ID_HERE))
await specificChannel.send(
f'{before.author} edited a message.\n'
f'Before: {before.content}\n'
f'After: {after.content}'
)
Useful link:
get_channel()
Discord.py documentation
maybe this can help u :)
#client.event
async def on_member_join(member:Member):
if member.bot:
guild:discord.Guild = member.guild
role = guild.get_role(config.botRoleID)
channel:discord.TextChannel = guild.get_channel(YOUR_CHANNEL_ID)
await member.add_roles(role)
await channel.send(f'Set Bot role to "{member.display_name}" 😌')

Using CTX in on_reaction_add event -- Discord.py

async def on_reaction_add(reaction, user):
emoji = reaction.emoji
if emoji == "💌":
await user.channel.send("HI")
I got problem here with user.
I want to use here with ctx like ctx.channel.send.
but also it occured error how to use ctx in here?
Instead of using the on_reaction_add event, it's better in this case to use a wait_for command event. This would mean the event can only be triggered once and only when the command was invoked. However with your current event, this allows anyone to react to a message with that emoji and the bot would respond.
By using client.wait_for("reaction_add"), this would allow you to control when a user can react to the emoji. You can also add checks, this means only the user would be able to use the reactions on the message the bot sends. Other parameters can be passed, but it's up to you how you want to style it.
In the example below shows, the user can invoke the command, then is asked to react. The bot already adds these reactions, so the user would only need to react. The wait_for attribute would wait for the user to either react with the specified emojis and your command would send a message.
#client.command()
async def react(ctx):
message = await ctx.send('React to this message!')
mail = '💌'
post = '📮'
await message.add_reaction(mail)
await message.add_reaction(post)
def check(reaction, user):
return user == ctx.author and str(
reaction.emoji) in [mail, post]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=10.0, check=check)
if str(reaction.emoji) == mail:
await ctx.send('Hi you just received')
if str(reaction.emoji) == post:
await ctx.send('Hi you just posted...')
You need to use reaction.message.channel.send
async def on_reaction_add(reaction, user):
emoji = reaction.emoji
if str(emoji) == "💌": await reaction.message.channel.send("HI")

I can't make the bot write that you don't have rights to use the command

I created a lot of moderation commands, and only allowed admins to use them.I also really want to make such a scheme:If a person who does not have the right to use the command writes it,the bot sends a message that you do not have the right to use this command.Please help me figure this out!
#client.command()
#commands.has_permissions(view_audit_log=True)
async def ban(ctx,member:discord.Member,reason):
emb = discord.Embed(title="ban",color=0xff0000)
emb.add_field(name='Модератор',value=ctx.message.author.mention,inline=False)
emb.add_field(name='Нарушитель',value=member.mention,inline=False)
emb.add_field(name='Причина',value=reason,inline=False)
await member.ban()
await channel.send(embed = emb)
You can use a error handler.
#client.command()
#commands.has_permissions(view_audit_log=True)
async def ban(ctx,member:discord.Member,reason):
emb = discord.Embed(title="ban",color=0xff0000)
emb.add_field(name='Модератор',value=ctx.message.author.mention,inline=False)
emb.add_field(name='Нарушитель',value=member.mention,inline=False)
emb.add_field(name='Причина',value=reason,inline=False)
await member.ban()
await channel.send(embed = emb)
#ban.error
async def ban_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the required permissions to use this command.')

Resources