Tool
v0.0.1
Discord-read-channelid
Get the latest messages from a discord channel
Tool ID
discord_read_channelid
Creator
@markus137
Downloads
52+

Tool Content
python
"""
title: Discord Reader
version: 0.0.1
changelog:
- 0.0.1 - Initial build.
"""

import requests
import json
import time
import os
import random
from typing import Awaitable, Callable
from pydantic import BaseModel, Field
from requests.models import Response


def retrieve_manymessages(channelid, multiples50=1):
    # this function is a stub. didnt add it in
    before = ""
    data = []
    for i in range(multiples50):

        r = retrieve_messages(channelid, before)
        json = r.json()
        data.append(json)
        if len(json) < 50:  # stop if we run out of messages
            break
        else:
            last_message = json[49]
            before = last_message["id"]

        time.sleep(random.uniform(1, 3))

    return data


class Tools:
    def __init__(self):
        pass

    class Valves(BaseModel):
        USER_AGENT: str = Field(
            default="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            description="The user agent to use when making requests to Reddit.",
        )
        authorization: str = Field(
            default="",
            description="open discord in browser -> f12 -> network -> record -> visit channel -> find messages/?limit=50 -> find authentication field",
        )

    async def get_messages(
        self,
        channelid: int,
        __event_emitter__: Callable[[dict], Awaitable[None]],
        __user__: dict = {},
    ) -> str:
        """
        Get the latest messages from a discord channel, as an array of JSON objects with the following properties: 'content','id','author','timestamp','edited_timestamp'
        :param channelid: The channelid to get the latest messages from.
        :return: A list of messages with the previously mentioned properties, or an error message.
        """
        headers = {
            "User-Agent": __user__["valves"].USER_AGENT,
            "authorization": __user__["valves"].authorization,
            "Referer": "https://discord.com/channels/@me/",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US,en;q=0.9",
            "referer": "https://discord.com/channels/@me/",
            "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"iOS"',
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.3",
        }

        await __event_emitter__(
            {
                "data": {
                    "description": f"Starting retrieval for channelID {channelid}.",
                    "status": "in_progress",
                    "done": False,
                },
                "type": "status",
            }
        )

        if channelid == 0:
            await __event_emitter__(
                {
                    "data": {
                        "description": f"Error: No channelid provided.",
                        "status": "complete",
                        "done": True,
                    },
                    "type": "status",
                }
            )
            return "Error: No channelid provided"

        try:

            response = requests.get(
                f"https://discord.com/api/v9/channels/{channelid}/messages?limit=50",
                headers=headers,
            )

            if not response.ok:
                await __event_emitter__(
                    {
                        "data": {
                            "description": f"Error: Failed to retrieve messages: {response.status_code}.",
                            "status": "complete",
                            "done": True,
                        },
                        "type": "status",
                    }
                )
                return f"Error: {response.status_code}"
            else:
                output = response.json()
                await __event_emitter__(
                    {
                        "data": {
                            "description": f"Retrieved {len(output)} messages from {channelid}.",
                            "status": "complete",
                            "done": True,
                        },
                        "type": "status",
                    }
                )
                return json.dumps(output)
        except Exception as e:
            await __event_emitter__(
                {
                    "data": {
                        "description": f"Failed to retrieve any messages from {channelid} Exception is: {e}.",
                        "status": "complete",
                        "done": True,
                    },
                    "type": "status",
                }
            )
            return f"Error: {e}"