discordjs / discord.js

A powerful JavaScript library for interacting with the Discord API
https://discord.js.org
Apache License 2.0
25.2k stars 3.96k forks source link

TypeError: Cannot read property 'channels' of undefined #6799

Closed Tomato6966 closed 2 years ago

Tomato6966 commented 2 years ago

Issue description

TypeError: Cannot read property 'channels' of undefined
    at Message.get channel [as channel] (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\structures\Message.js:357:24)
    at Function.flatten (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\util\Util.js:37:26)
    at Message.toJSON (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\structures\Base.js:35:17)
    at Message.toJSON (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\structures\Message.js:901:18)
    at JSON.stringify (<anonymous>)
    at serialize (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\enmap\node_modules\serialize-javascript\index.js:192:20)
    at Map.[_internalSet] (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\enmap\src\index.js:1211:22)
    at Map.set (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\enmap\src\index.js:273:23)
    at Map.ensure (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\enmap\src\index.js:644:12)
    at Client.<anonymous> (D:\.MIRATO\Public Bots\Clan Bot\srcv13\handlers\suggest.js:18:21)
    at Client.emit (node:events:406:35)
    at MessageCreateAction.handle (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
    at Object.module.exports [as MESSAGE_CREATE] (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)
    at WebSocketShard.onPacket (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
    at WebSocket.onMessage (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\event-target.js:199:18)
    at WebSocket.emit (node:events:394:28)
    at Receiver.receiverOnMessage (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\websocket.js:1022:20)
    at Receiver.emit (node:events:394:28)
    at Receiver.dataMessage (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\receiver.js:522:14)
    at Receiver.getData (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\receiver.js:440:17)
    at Receiver.startLoop (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\receiver.js:148:22)
    at Receiver._write (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\receiver.js:83:10)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Receiver.Writable.write (node:internal/streams/writable:334:10)
    at TLSSocket.socketOnData (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\node_modules\ws\lib\websocket.js:1116:35)

Code sample

const client = new Discord.Client({
  fetchAllMembers: false,
  restTimeOffset: 0,
  failIfNotExists: false,
  restWsBridgetimeout: 100,
  shards: "auto",
  allowedMentions: {
    parse: ["roles", "users"],
    repliedUser: false,
  },
  partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
  intents: [ 
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MEMBERS,
    Discord.Intents.FLAGS.GUILD_BANS,
    Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
    Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
    Discord.Intents.FLAGS.GUILD_WEBHOOKS,
    Discord.Intents.FLAGS.GUILD_INVITES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_PRESENCES,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
  ],
});

client.on("messageCreate", m => {
   console.log(m.content)
})

discord.js version

13.2.0

Node.js version

16.7

Operating system

Windows 11

Priority this issue should have

High (immediate attention needed)

Which partials do you have configured?

CHANNEL, MESSAGE, REACTION

Which gateway intents are you subscribing to?

GUILDS, GUILD_MEMBERS, GUILD_EMOJIS_AND_STICKERS, GUILD_INTEGRATIONS, GUILD_WEBHOOKS, GUILD_INVITES, GUILD_VOICE_STATES, GUILD_PRESENCES, GUILD_MESSAGES, GUILD_MESSAGE_REACTIONS, GUILD_MESSAGE_TYPING

I have tested this issue on a development release

No response

ImRodry commented 2 years ago

You have to initialize your client before receiving events.

The issue tracker is for issues within the library. If you have questions on how to use it, please use the Discord server

Tomato6966 commented 2 years ago

the client is initialized, i have all events ready event works voicestateupdate event works interactioncreate event works

the messageCreate event worked but just randomly now the event stopped working.... (after the bot was running for over 15minutes)

Tomato6966 commented 2 years ago

i could send the code, but i have 31793092 lines of code shall i send it? I am using a handler ofc

ImRodry commented 2 years ago

In your client you never log in and never acknowledge the ready event, which is why you're receiving that error - your client is not defined inside Discord's classes

Tomato6966 commented 2 years ago

Thats not the whole code... Let me send my whole index

Tomato6966 commented 2 years ago

/**********************************************************
 * @INFO  [TABLE OF CONTENTS]
 * 1  Import_Modules
   * 1.1 Validating script for advertisement
 * 2  CREATE_THE_DISCORD_BOT_CLIENT
 * 3  Load_Discord_Buttons_and_Discord_Menus
 * 4  Create_the_client.memer
 * 5  create_the_languages_objects
 * 6  Raise_the_Max_Listeners
 * 7  Define_the_Client_Advertisments
 * 8  LOAD_the_BOT_Functions
 * 9  Login_to_the_Bot
 * 
 *   BOT CODED BY: Tomato6966 | https://milrato.eu
 *********************************************************/

/**********************************************************
 * @param {1} Import_Modules for this FIle
 *********************************************************/
const Discord = require("discord.js");
const colors = require("colors");
const enmap = require("enmap"); 
const fs = require("fs"); 
//1.1 Validating script
if(!fs.existsSync("./botconfig/advertisement.json")){
  const data = {
    "adenabled": true,
    "statusad": { "name": "Bero-Host.de | Host Bots, Websites and Games 4 CHEAP", "type": "PLAYING", "url": "https://twitch.tv/#" },
    "spacedot": "・",
    "textad": "> ***[Milrato Development](https://discord.gg/milrato) partnered with:***\n> [**Bero-Host.de**](https://bero.milrato.eu)"
  }
  fs.writeFileSync("./botconfig/advertisement.json", JSON.stringify(data), err => {
    if(err){
      console.log(err)
      return;
    }
  })
}
const emojis = require("./botconfig/emojis.json")
const config = require("./botconfig/config.json")
const advertisement = require("./botconfig/advertisement.json")
const { delay } = require("./handlers/functions")

/**********************************************************
 * @param {2} CREATE_THE_DISCORD_BOT_CLIENT with some default settings
 *********************************************************/
const client = new Discord.Client({
  fetchAllMembers: false,
  restTimeOffset: 0,
  failIfNotExists: false,
  restWsBridgetimeout: 100,
  shards: "auto",
  allowedMentions: {
    parse: ["roles", "users"],
    repliedUser: false,
  },
  partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
  intents: [ Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MEMBERS,
    Discord.Intents.FLAGS.GUILD_BANS,
    Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
    Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
    Discord.Intents.FLAGS.GUILD_WEBHOOKS,
    Discord.Intents.FLAGS.GUILD_INVITES,
    Discord.Intents.FLAGS.GUILD_VOICE_STATES,
    Discord.Intents.FLAGS.GUILD_PRESENCES,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
    Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
    //Discord.Intents.FLAGS.GUILD_MESSAGE_TYPING,
    Discord.Intents.FLAGS.DIRECT_MESSAGES,
    Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
    //Discord.Intents.FLAGS.DIRECT_MESSAGE_TYPING
  ],
  presence: {
    activity: {
      name: `${config.status.text}`.replace("{prefix}", config.prefix), 
      type: config.status.type, 
      url: config.status.url
    },
    status: "online"
  }
});

/**********************************************************
 * @param {4} Create_the_client.memer property from Tomato's Api 
 *********************************************************/
const Meme = require("memer-api");
client.memer = new Meme("TOKEN"); //GET a TOKEN HERE: https://discord.gg/Mc2FudJkgP

/**********************************************************
 * @param {5} create_the_languages_objects to select via CODE
 *********************************************************/
client.la = { }
var langs = fs.readdirSync("./languages")
for(const lang of langs.filter(file => file.endsWith(".json"))){
  client.la[`${lang.split(".json").join("")}`] = require(`./languages/${lang}`)
}
Object.freeze(client.la)
//function "handlemsg(txt, options? = {})" is in /handlers/functions 

/**********************************************************
 * @param {6} Raise_the_Max_Listeners to 23 (default 10)
 *********************************************************/
client.setMaxListeners(23);
require('events').defaultMaxListeners = 23;

/**********************************************************
 * @param {7} Define_the_Client_Advertisments from the Config File
 *********************************************************/
client.ad = {
  enabled: advertisement.adenabled,
  statusad: advertisement.statusad,
  spacedot: advertisement.spacedot,
  textad: advertisement.textad
}

/**********************************************************
 * @param {8} LOAD_the_BOT_Functions 
 *********************************************************/
//those are must haves, they load the dbs, events and commands and important other stuff
function requirehandlers(){
  client.basicshandlers = Array(
    "extraevents", "loaddb", "clientvariables", "command", "events", "erelahandler", "slashCommands"
  );
  client.basicshandlers.forEach(handler => {
    try{ require(`./handlers/${handler}`)(client); }catch (e){ console.log(e.stack ? String(e.stack).grey.italic.dim : String(e).grey.italic.dim) }
  });
}requirehandlers();
module.exports.requirehandlers = requirehandlers;

//they are loading just the social loggers
function requiresociallogs(){
  client.socialhandlers = Array(
    "twitterfeed", /*"twitterfeed2",*/ "livelog", "youtube", "tiktok"
  );
  client.socialhandlers.forEach(handler=>{
    try{ require(`./social_log/${handler}`)(client); }catch (e){ console.log(e.stack ? String(e.stack).grey.italic.dim : String(e).grey.italic.dim) }
  })
}requiresociallogs();
module.exports.requiresociallogs = requiresociallogs;

//they are loading all other functions
function requireallhandlers(){
  client.allhandlers = Array(
    "anti_nuke",
    "apply", "apply2", "apply3", "apply4", "apply5",
    "ticket", "ticket2", "ticket3", "ticket4", "ticket5", "ticketevent",
    "roster", "roster2", "roster3",
    "welcome", "leave",
    "jointocreate", "logger", "reactionrole", "ranking",
    "antidiscord", "antilinks","anticaps", "blacklist", "keyword",
    "membercount", "autoembed", "suggest", "validcode", "dailyfact", "autonsfw",
    "aichat", "mute", "automeme", "counter"
  )
  client.allhandlers.forEach(handler => {
    try{ require(`./handlers/${handler}`)(client); }catch (e){ console.log(e.stack ? String(e.stack).grey.italic.dim : String(e).grey.italic.dim) }
  });
  require("fs").readdirSync("./handlers/applies").forEach(file=>{
    try{ require(`./handlers/applies/${file}`)(client); }catch (e){ console.log(e.stack ? String(e.stack).grey.italic.dim : String(e).grey.italic.dim) }
  })
  require("fs").readdirSync("./handlers/tickets").forEach(file=>{
    try{ require(`./handlers/tickets/${file}`)(client); }catch (e){ console.log(e.stack ? String(e.stack).grey.italic.dim : String(e).grey.italic.dim) }
  })
}requireallhandlers();
module.exports.requireallhandlers = requireallhandlers;

/**********************************************************
 * @param {9} Login_to_the_Bot
 *********************************************************/
client.login(config.token);
Tomato6966 commented 2 years ago

again the message event, was working, after 15 minute i got that error

Tomato6966 commented 2 years ago

It also happens with the example bot of https://discord.js.org

SpaceEEC commented 2 years ago

Can you post the stack trace of the error thrown when you use said example?

Tomato6966 commented 2 years ago
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'ping') {
    await interaction.reply('Pong!');
  }
});

client.login('MY TOKEN IS HERE');

Error:

Logged in as Tomato Personal Testing Bot#4763

TypeError: Cannot read property 'channels' of undefined
    at Interaction.get channel [as channel] (D:\.MIRATO\Public Bots\Clan Bot\srcv13\node_modules\discord.js\src\structures\Interaction.js:102:24)
SpaceEEC commented 2 years ago

I'm unable to reproduce this error. It seems like you somehow have undefined as your client for your interaction (or message for the initial error).

Would you mind going into node_modules/discord.js/src/structures/Interaction.js and verify the client is correctly passed to the constructor? (Simply logging it would be enough)

Tomato6966 commented 2 years ago

This is what i get

https://sourceb.in/HrZ4phWOg7

Put it in a sourcebin so its easier to read

SpaceEEC commented 2 years ago

You can use collapsible sections to directly put larger block of code into a comment. Avoids linking to sites such as these.

Maybe the client is overwritten somewhere then? Can you make Base#client actually readonly (why isn't it in the first place?) by modifying it, so an error should be thrown: node_modules/discord.js/src/structures/Base.js

+ Object.defineProperty(this, 'client', { value: client, writable: false });
- Object.defineProperty(this, 'client', { value: client });
Tomato6966 commented 2 years ago

This did the Trick but why with the discord.js.org example it didnt work?

SpaceEEC commented 2 years ago

This effectively did not change anything, writable: false is the default, overwriting it should error already.

The example is working fine for me, I'd like to know too why the client is somehow undefined for you.

Tomato6966 commented 2 years ago

I would like to know that too