Search code examples
pythondiscorddiscord.py

How can use ephemeral message?


import discord
from discord.ext import commands
import pandas as pd
import FinanceDataReader as fdr
from bs4 import BeautifulSoup
import requests
import locale

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='/', intents=intents)

player = {}
confirm = {}

@bot.event
async def on_ready():
    print(f'Login Bot: {bot.user}')

@bot.command()
async def 주식가격(ctx, *name):
    stock_t = ' '.join(name) 
    df_krx = fdr.StockListing('KRX')
    df_krx.to_csv('stock.csv')
    symbols = pd.read_csv('./stock.csv')
    try:
        code = symbols[symbols['Name'] == stock_t]['Code'].iloc[0]
        url = f"https://finance.naver.com/item/main.nhn?code={code}"
        result = requests.get(url)
        bs_obj = BeautifulSoup(result.text, 'html.parser')
        no_today = bs_obj.find('p', {"class": "no_today"})
        blind_now = no_today.find("span", {"class": "blind"})
        await ctx.send(f'{stock_t}의 현재 가격: {blind_now.text}원', ephemeral=True)
    except IndexError:
        await ctx.send(f"주식 이름 '{stock_t}'을 찾을 수 없습니다.", ephemeral=True)
    except Exception as e:
        await ctx.send(f"오류가 발생했습니다: {e}", ephemeral=True)

ephemeral is not working. How can solve this? not good at English sorry.😢

The above code is functioning correctly, and ephemeral messages are working as intended.


Solution

  • As the documentation says,

    [ephemeral] is only applicable in contexts with an interaction.

    Link: send

    What this means is that this only works with discord.Interaction, which include discord.ui.Button, discord.ui.Select, app_commands.command.

    This is an example of an ephemeral message through a slash command.

    import discord
    from discord import app_commands
    
    client = discord.Client(intents=discord.Intents.default())
    tree = app_commands.CommandTree(client)
    
    @tree.command(name="mycommand", description="Command description")
    async def mycommand_callback(interaction: discord.Interaction): #  This is the context, discord.Interaction
        await interaction.response.send_message(content="Hello World!",
                                                ephemeral=True)
    

    This would send an ephemeral message. Since you are using it in the context of commands.Context, the ephemeral parameter in the send method is ignored.