So I've been trying to make this work for about 3 hours now, and I' almost giving up.
My current code is:
var tmi = require('tmi.js');
var linksDisallowed = ["http://", "https://", ".dk"];
var options = {
options: {
debug: true
},
connection: {
cluster: "aws",
reconnect: true
},
identity: {
username: "botstormen",
password: "**CENSORED FOR SECURITY REASONS**"
},
channels: ["dunkstormen"]
};
var client = new tmi.client(options);
client.connect();
client.on('connected', function(adress, port) {
client.action("dunkstormen", "joinede chatten og er klar til at hjælpe! :3");
});
client.on('chat', function(channel, user, message, self) {
if(message === "!social" || message === "!Social") {
client.action("dunkstormen", "Twitter: twitter.com/dunkstormen Facebook: facebook.com/dunkstormen");
}
});
client.on('chat', function(channel, user, message, self) {
for (var i = 0; i < 3; i++) {
if(message.indexOf(linksDisallowed[i]) >= 0) {
client.say("Hello, " + user);
}
}
});
But whenever I type one of the word in the array linksDisallowed into the chat the bot just instantly crashes with the following error:
C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\commands.js:207
if (message.toLowerCase().startsWith("/me ") || message.toLowerCase().startsWith("\\me ")) {
^
TypeError: Cannot read property 'toLowerCase' of undefined
at client.say (C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\commands.js:207:20)
at client.<anonymous> (C:\Users\Benjamin Jørgensen\Desktop\botstormen\app.js:37:11)
at client.EventEmitter.emit (C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\events.js:99:50)
at client.handleMessage (C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\client.js:792:34)
at C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\client.js:919:18
at Array.forEach (native)
at client._onMessage (C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\lib\client.js:917:11)
at WebSocket.onMessage (C:\Users\Benjamin Jørgensen\Desktop\botstormen\node_modules\tmi.js\node_modules\ws\lib\WebSocket.js:442:14)
at emitTwo (events.js:87:13)
at WebSocket.emit (events.js:172:7)
tmi.js command say takes 2 arguments, you are passing only one.
https://docs.tmijs.org/v0.0.29/Commands.html#say
Change client.say("Hello, " + user); to client.say(channel,"Hello, " + user);
EDIT to help about comment:
According to docs, https://docs.tmijs.org/v0.0.29/Events.html#chat the chat event returns a user object. There is the description of a user object just below with a notice about it can change... But you can certainly do this for now: replace user by user.username .
If it does not work, inspect the user object to find the right property you should use.
That would mean your app.js isn't sending a message into the tmi.js service
Related
I use Express ( node.js ) and MongoDB. When I try to view or update user profile I get an error
middleware token check worked
getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (reading 'minAge')
at module.getProfileFields (C:\localhost\website\app\controllers\api\profile.js:34:22)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
it seems problem with this part of code
module.getProfileFields = async (req, res) => {
var successMessage = { status: 'success', message:"", data:{}};
var failedMessage = { status: 'fail', message:"", data:{}};
try {
var profileFields = await model.ProfileFields.find({isDeleted:false},{slug:1, options:1,type: 1});
var obj = {
...
educationLevel: [],
hobbies: [],
whatYouSay: [],
minAge: settings.minAge ? settings.minAge : 0,
maxAge: settings.maxAge ? settings.maxAge : 0,
religion: []
};
}
successMessage.message = "Successfully loaded profile reference";
successMessage.data = obj;
res.send(successMessage);
} catch (e) {
console.log('getProfileFields:::::::::::::>>>>e: ',e);
failedMessage.message = "Something went wrong";
res.send(failedMessage);
}
}
How to solve this problem?
Settings are empty, maybe they are not exported correctly. Check your settings file.
I think you're not using the find API call for MongoDB properly,
find usually takes up a filter object and an object of properties as a second argument.
Check the syntax required for find(){} function and probably you'll get through with it.
Hope it helps.
Happy coding!!
So I made this kick command and I finished coding it. Now I am getting this error and have literally no idea how to fix it. I searched through the internet for an hour now and have still no idea where the issue is.
Here is the error:
TypeError: options.getMember is not a function
at Object.execute (/Users/Aplex/Documents/Aplel/Commands/Moderation/kick.js:32:32)
at Object.execute (/Users/Aplex/Documents/Aplel/Events/Interaction/interactionCreate.js:21:21)
at Client.<anonymous> (/Users/Aplex/Documents/Aplel/Structures/Handlers/Events.js:18:54)
at Client.emit (node:events:538:35)
at InteractionCreateAction.handle (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/actions/InteractionCreate.js:74:12)
at Object.module.exports [as INTERACTION_CREATE] (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
at WebSocketShard.onPacket (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Users/Aplex/Documents/Aplel/node_modules/ws/lib/event-target.js:199:18)
And here is my code:
const { Client, CommandInteraction } = require("discord.js");
module.exports = {
name: "kick",
description: "Kick a member",
userPermission: ["KICK_MEMBERS"],
options: [
{
name: "target",
description: "target to kick",
type: "USER",
required: true
},
{
name: "reason",
description: "reason for this kick",
type: "STRING",
required: false,
}
],
/**
*
* #param {Client} client
* #param {CommandInteraction} interaction
* #param {String} args
*/
execute: async(client, interaction, args) => {
const { options, member } = interaction;
const target = options.getMember("target");
const reason = options.getString("reason") || "No reason provided";
if(!target.roles.highest.position >= member.roles.highest.position) return interaction.followUp({content: "You can't take action on this user as their role is higher than yours!",
});
await target.send(`You have been kicked from ${interaction.guild.name}, reason ${reason}`);
target.kick(reason);
interaction.followUp({content: `Kicked ${target.user.tag} successfully! reason: ${reason}`});
},
};
Anyone know where the issue is here? It would be really appreciated if someone helped!
can I assume you are following lyxcode tutorials?
If so, in the line
execute(client, interaction, args)
change it to
execute(interaction, client, args)
this should then match your interactionCreate file.
also, change followUp to reply
hopefully this fixes it for you!
If you are trying to get the member's account cache, maybe you should try something like this:
client.members.cache.get('User ID');
An error started popping up for me when I added the "wiezienie.send ("test");" function.
My error is:
TypeError: Cannot read property 'send' of undefined
at Object.run (C:\Users\User\Desktop\ZukBot-master\src\commands\warn.command.js:63:19)
at Client.<anonymous> (C:\Users\User\Desktop\ZukBot-master\src\handlers\command.handler.js:126:11)
at Client.emit (events.js:327:22)
at MessageCreateAction.handle (C:\Users\User\Desktop\ZukBot-master\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\User\Desktop\ZukBot-master\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\User\Desktop\ZukBot-master\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\User\Desktop\ZukBot-master\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\User\Desktop\ZukBot-master\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\User\Desktop\ZukBot-master\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
My code is:
const {
Permissions: { FLAGS }, Message, Client,
} = require("discord.js")
const { MessageEmbed } = require("discord.js")
const client = new Client({ partials: ['MESSAGE', 'REACTION'] });
module.exports = {
name: "warn",
description: "Ostrzegasz kogoś",
args: true,
usage: "<użytkownik>",
botPermissions: [FLAGS.BAN_MEMBERS],
userPermissions: [FLAGS.BAN_MEMBERS],
run(msg, args, message) {
let wiezienie = client.channels.cache.get("761902640552083466")
msg.delete().catch(O_o=>{});
const { channel, guild, mentions, author } = msg
const userArg = args[0]
const reasonArg = [...args].slice(1).join(" ")
const userToKick = mentions.users.first()
if (!userToKick) {
msg.author.send(`⛔ Wystąpił problem szefie! \`Nie ma takiego gracza na serwerze!\``)
return
}
if (userToKick.id === author.id) {
msg.author.send(`⛔ Wystąpił problem szefie! \`Nie możesz otrzegać siebie byczku!\``)
return
}
const memberToKick = guild.members.cache.get(userToKick.id)
if (!memberToKick.kickable) {
msg.author.send(`⛔ Wystąpił problem szefie! \`Bot nie ma permisji do ostrzeżenia tego użytkownika!\``)
return
}
const wsukces = new MessageEmbed()
// Set the title of the field
.setTitle(`⛔ Więzienie`)
// Set the color of the embed
.setColor(0xec5454)
// Set the main content of the embed
.setDescription("Użytkownik został wtrącony do więzienia na godzinę. Nałożono ostrzeżenie")
memberToKick.roles.add("761901722305298432")
memberToKick.roles.remove("724576322952888422")
const ksukces = new MessageEmbed()
// Set the title of the field
.setTitle(`⛔ Zostałeś wtrącony do więzienia/ostrzeżony na serwerze \`among us gang\``)
// Set the color of the embed
.setColor(0xec5454)
// Set the main content of the embed
.setDescription("Zostałeś wtrącony do więzienia, czyli administrator nałożył na twoje konto ostrzeżenie. Posiadasz dostęp do jedynie najważniejszych informacji")
.addField("Okres:", "Patrząc na twoją aktywną liczbę ostrzeżenień, w więzieniu pozostaniesz jeszcze godzinę", true)
.setFooter("Zostałeś ostrzeżony!")
memberToKick.send(ksukces)
channel.send (wsukces)
wiezienie.send("test");
setTimeout(function(){
memberToKick.roles.add("724576322952888422")
memberToKick.roles.remove("761901722305298432")
memberToKick.send("Twoje ostrzeżenie zniknęło. Miej się na baczności!")
}, 3600000); //time in milliseconds
}
}
You are getting this error because you are trying to access the send property of an undefined variable wiezienie.
You should check this line:
let wiezienie = client.channels.cache.get("761902640552083466")
Most likely it's not returning what you expect it to.
I also got an error like this.
Try to change this line
let wiezienie = client.channels.cache.get("761902640552083466")
into
let wiezienie = client.channels.fetch("761902640552083466")
the code works fine, cause i'm following an online crash course. my problem is when i enter selfdestruct() it says something about an error, that i am unsure of what. please have a look, and see what is the problem.
here is the code on where the problem pops out every-time i add this:
address payable admin;
function endSale() public {
require(msg.sender == admin, "must be admin");
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
selfdestruct(admin);
}
note that the error only shows when i add
selfdestruct(admin)
this is the test driven fashion code:
it('ends the token sale', () => {
return DappToken.deployed().then((instance) => {
//grab token instance first
tokenInstance = instance;
return DappTokenSale.deployed();
}).then((instance) => {
//then grab token sale instance
tokenSaleInstance = instance;
//try to end the sale from account other than the admin
return tokenSaleInstance.endSale({ from: buyer });
}).then(assert.fail).catch((error) => {
assert(error.message.indexOf('revert') >= 0, 'must be admin to end sale');
//end sale as admin
return tokenSaleInstance.endSale({ from: admin});
}).then((receipt) => {
//receipt
return tokenInstance.balanceOf(admin);
}).then((balance) => {
//return unsold dapp tokens to admin
assert.equal(balance.toNumber(), 999990, 'returns all unsold dapp tokens to admin');
// check that the token price was reset when the selfDestruct was called
return tokenSaleInstance.tokenPrice();
}).then((price) => {
assert.equal(price.toNumber(), 0, 'token price was reset');
});
});
i'm using pragma ^0.5.0
here's my error log:
Error: Returned values aren't valid, did it run Out of Gas?
at ABICoder.decodeParameters (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-eth-abi\src\index.js:226:1)
at Contract._decodeMethodReturn (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-eth-contract\src\index.js:465:1)
at Method.outputFormatter (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-eth-contract\src\index.js:818:1)
at Method.formatOutput (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-eth-contract\~\web3-core-method\src\index.js:163:1)
at sendTxCallback (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-eth-contract\~\web3-core-method\src\index.js:473:1)
at C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-core-requestmanager\src\index.js:147:1
at C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-provider\wrapper.js:112:1
at XMLHttpRequest.request.onreadystatechange (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\web3-providers-http\src\index.js:96:1)
at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request-event-target.js:34:1)
at XMLHttpRequest._setReadyState (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request.js:208:1)
at XMLHttpRequest._onHttpResponseEnd (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request.js:318:1)
at IncomingMessage.<anonymous> (C:\Users\KimVillanueva\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~\xhr2-cookies\dist\xml-http-request.js:289:47)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
I am novice to NodeJs and working with ebay-api.
I found this great example at GitHub
one strange issue is when I run the js file via CMD. it is working but sometimes it shows error and then I cleared cache it works and sometimes after clearing the cache it shows error. But the code is exactly the same which I got output correctly. Did anyone face the same issue or any idea where might be the problem?
var ebay = require('../index.js');
var params = {
keywords: ["Canon", "Powershot"],
// add additional fields
outputSelector: ['AspectHistogram'],
paginationInput: {
entriesPerPage: 10
},
itemFilter: [
{name: 'FreeShippingOnly', value: true},
{name: 'MaxPrice', value: '150'}
],
domainFilter: [
{name: 'domainName', value: 'Digital_Cameras'}
]
};
ebay.xmlRequest({
serviceName: 'Finding',
opType: 'findItemsByKeywords',
appId: '<your app id>', // FILL IN YOUR OWN APP KEY
params: params,
parser: ebay.parseResponseJson // (default)
},
// gets all the items together in a merged array
function itemsCallback(error, itemsResponse) {
if (error) throw error;
var items = itemsResponse.searchResult.item;
console.log('Found', items.length, 'items');
for (var i = 0; i < items.length; i++) {
console.log('- ' + items[i].title);
console.log('- ' + items[i].galleryURL);
console.log('- ' + items[i].viewItemURL);
}
}
);
I'm getting the following errors:
C:\node_modules\ebay-api\examples> node H:\NodeJs\app.js //Run via NodeJS CMD
H:\NodeJs\app.js:36
if (error) throw error;
^
Error
at Request._callback (C:\Users\shiva raju\node_modules\ebay-api\lib\xml-request.js:151:23)
at Request.self.callback (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:200:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:194:7)
at Request. (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:1067:10)
at emitOne (events.js:101:20)
at Request.emit (events.js:191:7)
at IncomingMessage. (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:988:12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
Your suggestions would be appreciated. Thanks
You can use this node module ebay-node-api where you can get the response data in form of JSON.
You can check this example to check how to consume ebay-node-api
https://github.com/pajaydev/ebay-node-api/
You are throwing an error object in the callback but you are not catching it anywhere in the code. Please handle the error you are throwing.