Search code examples
pythonserverdiscordbots

Make Hikari discord bot only listen to one channel


I just mada a discord bot with hikari that for now listens to a whole server, and if someone types

$shares https://tiktok.com/@xxx/2938923

It runs a script, that sends shares to that tiktok video. Because there is a lot of members in the server, The channel members are supposed to write the comand in has a cooldown. But because the bot listens to the whole server, they could just type the command in another channel without cooldown.

This is my code for now:

import hikari
import time

bot = hikari.GatewayBot(token="xxx")


@bot.listen()


async def ping(event: hikari.GuildMessageCreateEvent) -> None:
    global link
    if event.is_bot or not event.content:
        return
    if event.content.startswith("$docu"):
        await event.message.respond(f"""To send shares, write **$shares**, followed by the TikTok url. 
        > Ex: **$shares https://tiktok.com/@xxx/29835027502**""")

    if event.content.startswith("$shares"):
        split = event.content.split()
        try:
            link = split[1]
            await event.message.respond(f"Sending 1k shares to <{split[1]}>")
            start_time = time.time()
            xshares()
            await event.message.respond(f"Shares Sent! | TTC > {round(time.time() - start_time, 1)}s | SPEED > {round(1100 / (time.time() - start_time), 1)}/s")

        except:
            await event.message.respond(f"Please include link!")


def xshares():
    #shares script (not relevant here)
    return
bot.run()

What can I add to this code to make it only listen to a certain channel (<#xxxxxx>)

Or should I use another discord python bot library?

Thanks for your help


Solution

  • GuildMessageCreateEvent has the channel_id attribute which contains the ID of the channel that the message was created in. You can use a simple if-statement guard to ensure that the command is only run in your chosen channel.

    For example:

    @bot.listen()
    async def message_listener(event: hikari.GuildMessageCreateEvent) -> None:
        # Replace with the required channel ID
        if event.channel_id != 1234567890:
            return