Deformat text in discord.py - python

I want to remove the formatting from text in discord.py - adding \ before *'s, ```'s etc. I have not yet been able to come up with a perfect solution.
Can anyone tell me what I could use?
I use discord.py and python 3

If this is in a command you can use commands.clean_content
#bot.command()
async def test(ctx, arg: commands.clean_content(fix_channel_mentions=False, use_nicknames=True, escape_markdown=True, remove_markdown=False)):
await ctx.send(arg)
All params are kwarg only and optional, for more info see the docs
If you want to escape markdown for some other text (e.g. from an API), you can use utils.escape_markdown
import discord
text = "Hello my name is **Wasi**"
print(discord.utils.escape_markdown(text))
# 'Hello my name is \*\*Wasi\*\*'
There is also utils.escape_mentions for removing mentions

Discord.py provides a utility function: discord.utils.escape_markdown
This converts:
#```python
#print("hello")
#```
#**bold** *italics*
into
#\`\`\`python
#print("hello")
#\`\`\`
#\*\*bold\*\* \*italics\*

Related

Basics - How do I output random.sample to newlines for a Discord bot?

My first time doing any coding, so apologies in advance.
I'm making a Discord bot for fun and am trying to get random.sample to output each selection to a new line.
Currently looks like this
Need it to look like:
Seed the Rebellion
Wreck the Place
Burn it Down
Code here:
import disnake
import random
from disnake.ext import commands
from variables import IntriguesList
class IntrigueCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.slash_command(guild_ids= [guildID])
async def intrigue(interaction: disnake.ApplicationCommandInteraction):
"""Generate Intrigues for an upcoming battle"""
await interaction.response.defer(with_message=True)
intrigue = disnake.Embed(
title="Intrigues",
description="Three side-missions for your next battle",
color = disnake.Colour.dark_green()
)
intrigue.add_field(name="Your Intrigues", value=f"{(random.sample(IntriguesList, 3))}")
Tried \n in various ways, but don't really know what I'm doing so help greatly appreciated!
You can use \n to enter a newline.
sample = random.sample(IntriguesList, 3)
sample_str = "\n".join(sample)
intrigue.add_field(name="Your Intrigues", value=sample_str)

Setting command parameter descriptions in discord.py

I am making a command in a bot to create a profile for a user. It is working fine, but I would like the description of the "name" parameter to say "What would you like to be called?".
Here is the code I currently have:
import discord
from discord import app_commands
#tree.command(name="makeprofile", description="Make your own profile!", guild=discord.Object(id=000000000000))
async def make_profile(interaction, preferred_name: str, pronouns: str):
db.insert({'id': interaction.user.id, 'name': preferred_name, 'pronouns': pronouns})
From the documentation:
#discord.app_commands.describe(**parameters)
Describes the given parameters by their name using the key of the keyword argument as the name.
So in your case:
#app_commands.describe(preferred_name = "What would you like to be called?")

How can i set multiple words as a single command in discord.py?

I want to set a command that has multiple words (for example a 'how old are you' command) in python but I am not sure how. My code looks like this:
#client.command(aliases=['how old are you'])
async def age(ctx):
await ctx.send('I am 30')
I tried the aliases thing but obviously I am missing something
If you have certain and few commands, use optional arguments;
async def how(ctx, *args):
items = ['old', 'are', 'you']
if items == args:
await ctx.send('I am 30.')
# Or add some fuzzy logic and combine the strings.
# items = [ ['old', 'is'], ['are', 'it'], ['going', 'you']]
# how is it going and how old are you
If you want to develop a complete bot, I guess it requires a little bit natural language processing, but I believe you can achieve your request as below. For NLP spacy could be an option.
It's a conceptual thought, I hope it would be helpful.
import spacy
nlp = spacy.load('en')
def nlp_spacy(arg):
doc = nlp(' '.join(arg))
# Below line gives you the object. F.e; age, you..
return [tok for tok in doc if (tok.dep_ == "nsubj")]
#bot.command()
async def how(ctx, *args):
objs= nlp_spacy(args)
if 'old' in objs:
await ctx.send('I'm 30')
Actually I made a mistake... Here's the corrected code, and I'm very sorry for "not telling the truth".
#client.event
async def on_message(ctx):
if ctx.message.content == "how old are you":
ctx.send("I am 30")
return
I would recommend you to just use an if statement such as:
#client.command()
async def age(ctx):
if ctx.message.content == "how old are you":
ctx.send("I am 30")
That is a very simple way to do it, and it should work totally fine. Otherwise I will recommend you to search on google, or check youtube out. There is a lot of usefull content :D

Wikipedia Command Discord.py

#commands.command()
#commands.cooldown(1,10,BucketType.user)
async def wiki(self,ctx,*,word):
def sum(arg):
definition = wikipedia.summary(arg,sentences=3,chars=1000)
return sum(word)
await ctx.send(sum)
I am making a Wiki command, it doesn't work as expected and responds with this:
That's because you are using sum the wrong way. Instead of this:
await ctx.send(sum)
you have to do this:
await ctx.send(sum(word))
Also, why are you invoking the function from within itself? In sum you should return definition.
Try not to shadow the builtin sum. You should rename the function to be get_definition or something else instead.

How to remove or change the default help command?

How do you remove or at least change the format of the default help command in discord.py?
I think changing the format would be nice, I don't really like the format at all.
Try this:
bot.remove_command('help')
Put this at the top of your code, after your imports.
Then create your own.
Or to format it check this out: Click here!
The proper way to disable the help command according to the docs is to pass help_command=None into the constructor for discord.ext.commands.Bot, such as:
bot = commands.Bot(help_command=None)
or
class MyBot(commands.Bot):
def __init__(self):
super().__init__(help_command=None)
This also allows you the opportunity to pass your own help function into the help_command argument for different formatting.
You will need to remove the command for example
client.remove_command('help')
you will need to put it under
client = commands.Bot
it will be like
client = commands.Bot(command_prefix = 'somethingelse')
client.remove_command('help')
Here you can use this:
intents = discord.Intents.all()
activity = discord.Game(name=f"!help in {len(client.guilds)} servers!")
client = commands.Bot(command_prefix="!", intents=intents, activity=activity, status=discord.Status.do_not_disturb, help_command=None)
This is how you should do it so that it preserves the behavior of the help command while letting you change how it looks:
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command```
See the documentation: https://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#help-commands for more details.
For migrating from old helpformatters: https://discordpy.readthedocs.io/en/rewrite/migrating.html#helpformatter-and-help-command-changes
You don't really need to remove the command... It isn't good, using the (prefix)help commandname <- It wont appear then... If you want it embed you can do.
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
client.help_command = NewHelpName()```
The built in help command is of great use

Categories

Resources