如何在使用interactions.py的Discord机器人中从单独的文件调用函数?

huangapple go评论70阅读模式
英文:

How can I call a function from a separate file when using Discord bot with interactions.py?

问题

Here's the translated code segment from your provided content:

这是我的 main.py 脚本
--------------------------

```python
import interactions
from Commands.music import join_voice_channel

# Tokens
bot = interactions.Client(token="my_bot_token")

# Login confirmation of bot in terminal
@bot.event
async def on_ready():
    print("Alleskönner is ready!")
    print("Interaction.py version =", interactions.__version__)

# The first command
@bot.command(
    name="my_first_command",
    description="这是我创建的第一个命令"
)
async def my_first_command(ctx: interactions.CommandContext):
    await ctx.send("你好!")

# Booting up the bot
bot.start()

Music.py 脚本

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# 设置 Spotify 认证
client_credentials_manager = SpotifyClientCredentials(client_id='YOUR_CLIENT_ID',
                                                      client_secret='YOUR_CLIENT_SECRET')
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

async def join_voice_channel(ctx):
    # 检查命令调用者是否在语音频道中
    if ctx.author.voice:
        channel = ctx.author.voice.channel
        voice_client = ctx.voice_client

        # 检查机器人是否已经在语音频道中
        if voice_client is None:
            await channel.connect()
        else:
            await voice_client.move_to(channel)
    else:
        await ctx.send('你需要加入一个语音频道才能使用此命令。')

如何在 main.py 中调用 join_voice_channel() 函数,以便当执行 main.py 脚本并使用 join VC 斜杠命令时,运行保存在 music.py 中的函数?

附加上下文

  • 我正在使用 interactions 库 4.4.0
  • join_voice_channel 函数旨在通过斜杠命令触发。
  • 我想在使用 join VC 斜杠命令时执行保存在 music.py 中的函数。

<details>
<summary>英文:</summary>

Here is my main.py script:
--------------------------

import interactions
from Commands.music import join_voice_channel

Tokens

bot = interactions.Client(token= "my_bot_token")

Login confirmation of bot in terminal

@bot.event
async def on_ready():
print(f"Alleskönner is ready!")
print(f"Interaction.py version = ",interactions.version)

The first command

@bot.command(
name="my_first_command",
description="This is the first command I made"
)
async def my_first_command(ctx: interactions.CommandContext):
await ctx.send("Hi there!")

Booting up the bot

bot.start()


Music.py script
-------------------------------


import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

Set up Spotify authentication

client_credentials_manager = SpotifyClientCredentials(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET')
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

async def join_voice_channel(ctx):
# Check if the command invoker is in a voice channel
if ctx.author.voice:
channel = ctx.author.voice.channel
voice_client = ctx.voice_client

    # Check if the bot is already in a voice channel
    if voice_client is None:
        await channel.connect()
    else:
        await voice_client.move_to(channel)
else:
    await ctx.send(&#39;You need to be in a voice channel to use this command.&#39;)

How do I call the function `join_voice_channel()` in `main.py` so that when the `main.py` script is executed and the `join VC` slash command is used it runs the function that is saved in `music.py`?

Additional Context
--------------------

* I am using the interactions library `4.4.0`.
* The `join_voice_channel` function is intended to be triggered by a slash command.
* I want to execute the function stored in `music.py` when the `join VC` slash command is used.

</details>


# 答案1
**得分**: 1

## 如何使用多个文件 ##
正如[Clement Genninasca](https://stackoverflow.com/users/15810170/clement-genninasca)所说,你需要使用cogs来实现这个功能。
在`discord.ext.commands.Bot()`中,可以使用`add_cog`来完成。

## 实现 ##
在这个示例中,我将使用两个文件:`main.py`和`file2.py`。

在`main.py`中:
```py
import discord
from discord.ext import commands
import file2

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)  # commands.Bot()可以添加cogs

@client.event
async def on_connect():
    await client.add_cog(file2.voice(client))  # 从file2中添加cog

注意:discord.Client()无法使用cogs。请查看文档

file2.py中:

from discord.ext import commands

class voice(commands.Cog):  # 创建commands.Cog类以放置命令
    def __init__(self, bot):
        self.bot = bot

    @commands.command()  # 测试cog命令
    async def test_cog(self, ctx):
        await ctx.send("Hello!")

输出

如何在使用interactions.py的Discord机器人中从单独的文件调用函数?

Slash命令示例

main.py中:

@client.event
async def on_ready():
    await client.load_extension('file2')
    await client.tree.sync()
    print(f'We have logged in as {client.user}')

file2.py中:

class voice(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="test_cog", description="Testing")
    async def test_cog(self, interaction: discord.Interaction):
        await interaction.response.send_message("Hello!")

async def setup(bot: commands.Bot) -&gt; None:
    await bot.add_cog(voice(bot))

输出:

如何在使用interactions.py的Discord机器人中从单独的文件调用函数?

有用的资源

英文:

How to use multiple files

As Clement Genninasca said, you'll need cogs for this.
add_cog in discord.ext.commands.Bot() can do this.

Implementation

For this example, I'll use two files. main.py and file2.py.

In main.py:

import discord
from discord.ext import commands
import file2

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix=&quot;!&quot;, intents=intents)  # commands.Bot() can add cogs

@client.event
async def on_connect():
    await client.add_cog(file2.voice(client))  # add cog from file2

Notes: discord.Client() can't use cogs. See the docs here.

In file2.py:

from discord.ext import commands


class voice(commands.Cog):  #create commands.Cog class to put commands in
    def __init__(self, bot):
        self.bot = bot

    @commands.command()  # test cog command
    async def test_cog(self, ctx):
        await ctx.send(&quot;Hello!&quot;)

Output

如何在使用interactions.py的Discord机器人中从单独的文件调用函数?

Slash commands example

In main.py:

@client.event
async def on_ready():
    await client.load_extension(&#39;file2&#39;)
    await client.tree.sync()
    print(f&#39;We have logged in as {client.user}&#39;)

In file2.py:

class voice(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name=&quot;test_cog&quot;, description=&quot;Testing&quot;)
    async def test_cog(self, interaction: discord.Interaction):
        await interaction.response.send_message(&quot;Hello!&quot;)


async def setup(bot: commands.Bot) -&gt; None:
  await bot.add_cog(voice(bot))

Output:

如何在使用interactions.py的Discord机器人中从单独的文件调用函数?

Helpful resources

huangapple
  • 本文由 发表于 2023年5月21日 21:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定