1
votes

I'm trying to make a bot that listens for messages in a channel and sends them to my private server. I don't fully understand coding stuff so I relied on some online sources.

I already have done a bot that gets the new messages in a channel then brings them to a private channel. I cannot find the GitHub where the code was located since I moved to another OS. Now that's out of the way, I need the bot to send the logs to my private server in case some of my staff accidentally deletes one of the logs/multiple log. Then I came across this similar question: How to send a message to a different server | Discord Bot , but I realized this was JavaScript not python. Nonetheless, I moved to that JavaScript and tried it.

Here's the Python bot that I got from a GitHub. It creates an embed of the message it listened and sends them to the channel it specified (#message-log). It also includes the the author's avatar and name

@client.event
async def on_message(message):
    guild = message.guild
    log_channel = discord.utils.get(guild.channels, name="message-log")
    if log_channel is None:
        await client.process_commands(message)
        return
    if not message.author.bot:
        embed=discord.Embed(
            color=0xffd700,
            timestamp=datetime.datetime.utcnow(),
            description="in {}:\n{}".format(message.channel.mention, message.content)
        )
        embed.set_author(name=message.author, icon_url=message.author.avatar_url)
        embed.set_footer(text=message.author.id)
        if len(message.attachments) > 0:
            embed.set_image(url = message.attachments[0].url)
        await log_channel.send(embed=embed)
        await client.process_commands(message)

Then here's the JavaScript code (this is not my focus, but I decided to include it for emergency). It gets the listened server guild ID and channel. I don't know if it's really capable of sending it to my private server since there are errors.

client.guilds.get(<guild id>).channels.get(<channel id>).send(<message>)

I also didn't include IDs for privacy reasons.

I anticipated that JavaScript would run like it would normally would, but it returned an error below.

TypeError: Cannot read property 'channels' of undefined
    at Object.<anonymous> (C:\Users\SomethingCube\Desktop\ListenBot\ListenBot.js:12:40)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Probably because the code I got (JavaScript) was made in 2018 and many things changed before I posted this, or I'm doing something wrong (I'm guessing that I placed the wrong prefix and suffix (I don't know what's that called) of the IDs, ("------------------")).

Again, JavaScript is not my focus here but Python. I'm looking for a code (for Python) that sends the messages to my private server.

1
from the outside if i understand, basically you need a python server, listening to particular messages and storing it somewhere is it ? and the server is accessed through it's specific IP ?venkata krishnan
I've seen some questions in this site before that got answers with a code. Though, those are made years ago and I don't know if they would still work.SomethingCube
You can use get_guild to get the guild you want to send the message to.Patrick Haugh
Just in case if you're confused, by what I meant of "listen", it watches out for new messages in channels (Discord).SomethingCube

1 Answers

0
votes

Welcome to StackOverflow, Cube! I have a simple Discord.py bot I've recently wrote to do the same thing, so I'll post the relevant code then explain it:

@bot.event
async def on_message(message):
    if len(message.content) > 250 or message.author.bot:
        return
    if message.guild:
        messageL = f"{message.author.name.replace(message.author.discriminator, '')} posted: '{message.content}'"
        success1 = await SendHomeMML(messageL)
        if success1 is None:
            print("Message Log message failed.")
        descE = f"{message.author.name.replace(message.author.discriminator, '')} posted: \n'{message.content}'\n" \
            f"This was in a Guild titled '{message.guild.name}' within Channel '{message.channel.name}'\n"
        MessageE = discord.Embed(title="Message Log", description=descE, colour=8421376)
        MessageE.set_footer(text=f"Posted on: {message.created_at.isoformat(' ')}")
        success2 = await SendHomeEML(MessageE)
        if success2 is None:
            print("Message Log embed failed.")
        # and so on...

# Some time later... #

async def SendHomeEML(embedded):
    return await bot.get_channel(123456789123456789).send(embed=embedded)

async def SendHomeMML(message):
    return await bot.get_channel(123456789123456789).send(content=discord.utils.escape_mentions(message))

First, the on_message bit: what am I doing? The length and bot check just determine that the message being analyzed wasn't posted by a bot (this is important, to prevent potentially infinite loops whenever your bot posts a message), and that the message isn't insanely long. Feel free to remove the length check if you're okay with your server getting those bulky posts. Next, we check to see if the message was sent in a guild; if not, that's going somewhere else that isn't relevant. What I prefer to do is send both a message and an embed of all posted messages, to different channels. That's what the SendHomeMML and SendHomeEML messages do. If you're curious, they stand for "Send (to) Home (Server) Message/Embed-Message Log." At any rate, it's not very complicated -- most of the code is just formatting the embed to look halfway decent. The part you're probably after is the implementation of those functions.

Formatting note: separating these into their own functions is not required, and would probably garner some disapproval due to the way it lengthens the code. But for a simple bot, readability in events/commands is king. This way, I can send a lot of things to my bot's "Home Server" (like your private server) without having to rewrite that line. These would also be solid places to put more error handling, depending on just how important it is that these messages get delivered.

Code Requirements:

  1. You will (obviously) have to import discord
  2. Place the channel ID(s) that you want as your destinations in the SendHome function
  3. Your bot must be in both the channels you input for Step 2, and naturally the channels in which the messages you're storing are posted.

Protip: Channel IDs are completely unique in Discord, hence why get_channel() does not require a Guild, only an ID. If your bot is not in the channel that corresponds to the ID you posted, you will receive an error.

If you have any questions, feel free to leave some comments. Cheers!