PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] How to replace multiple words in a line with another words

 July 09, 2022     discord, discord.py, keyword, replace     No comments   

Issue

i have recently started building a bot in discord.py and got stuck in this situation here

@client.command()
async def replace(ctx, *, arg):
     msg = f"{arg}" .format(ctx.message).replace('happe', '<:happe:869470107066302484>')
     await ctx.send(msg)

this is a command which replaces the word "happe" with the emoji so this looks like :

Command : {prefix}replace i am very happe

Result : i am very "emoji for happe"

but i want to make it so we can replace multiple words with different emoji and not just a single one like

Command : {prefix}replace i am not happe, i am sad

Result : i am not "emoji for happe", i am "emoji for sad"

is there a way to edit multiple words in just one sentence like using a json file of making a list of emojis and its id? also this command doesnt seems to work in cogs and says command is invalid


Solution

is there a way to edit multiple words in just one sentence like using a json file ot making a list of emojis and its id?

Yes, you can do just that. Make a list of word-emoji pairs and iterate over all of them to replace every word.

async def replace(ctx, *, arg):
    l = [("happe", "<:happe:869470107066302484>"), ("sad", "..."), ...]
    msg = arg  # Making a copy here to avoid editing the original arg in case you want to use it at some point
    for word, emoji in l:
        msg = msg.replace(word, emoji)
    await ctx.send(msg)

also this command doesnt seems to work in cogs and says command is invalid

In cogs the decorator is @commands.command(), not @client.command(). Don't forget the from discord.ext import commands import to get access to it.

Lastly, I'm a bit confused what f"{arg}" .format(ctx.message) is supposed to be doing? You can remove the .format and the f-string entirely. args is already a string so putting it in an f-string with nothing else has no effect, and .format(ctx.message) doesn't do anything either. The result of that entire thing is the same as just arg.

>>> arg = "this is the arg"
>>> f"{arg}".format("this has no effect")
'this is the arg'


Answered By - stijndcl
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing