How to clear chat NODE JS telegram bot (node-telegram-bot-api.) - node.js

Hi guys i'm junior nodejs developper!
my question: How to clear chat on write text == cls
my code
const { chat, message_id } = message
const chatId = message.chat.id
const name = message.from.first_name
const text = message.text
// ================== on write "cls" clear chat
else if (text == 'cls') {
bot.deleteMessage(chatId, chat.id)
var msg = message;
}

I think currently there isn't any method to clear whole chat using bot but
you can use simple loop to delete last 100 messages(only work for group chats and bot should have admin permission to delete messages). Like this,
const Telegram = require('node-telegram-bot-api')
const TOKEN = process.env.TOKEN || "<YOUR BOT TOKEN>";
const bot = new Telegram(TOKEN,{polling:true})
bot.onText(/\/start/,(msg)=>{
bot.sendMessage(msg.chat.id,'Hello World!')
})
//I use bot command regex to prevent bot from miss understanding any user messages contain 'cls'
bot.onText(/\/cls/,(msg)=>{for (let i = 0; i < 101; i++) {
bot.deleteMessage(msg.chat.id,msg.message_id-i).catch(er=>{return})
//if there isn't any messages to delete bot simply return
}
}
)
Hopefully this might help you :D
Refer:
https://core.telegram.org/bots/api#deletemessage
Note: I'm a beginner, so if there are any mistakes, please excuse me.

Related

How to send a message if user has the permission

Okay so, im trying to make an announce command that makes the bot say what the user asks it to write,
the command is working fine but the main problem is that i dont want users that are not moderators/admins to use this command i tried to use if (user.hasPermission("KICK_MEMBERS") but i simply don't know how to implement this into my code, (here it is)
const Discord = require('discord.js');
module.exports = {
name: 'announce',
description: "announce",
execute(message, args){
const developerEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`failed to send message`)
.setAuthor('♥Aiko♥', 'https://i.imgur.com/1q9zMpX.png')
.setDescription('please mention the channel first(if this promblem persists contact the developer)')
.setTimestamp()
.setFooter(`©Revenge#7005 | Requested by ${message.author.tag}.`);
if(message.mentions.channels.size === 0) {
message.channel.send(developerEmbed);
}
else {
let targetChannel = message.mentions.channels.first();
const args = message.content.split(" ").slice(2);
let userMessage = args.join(" ");
targetChannel.send(userMessage);
message.delete();
}
}
}
so yeah, any ideas how to make the bot check for the permission and then send the message if the user has it?
i'm pretty new to coding and this bot is my first bigger project so sorry if this question seems stupid
Make sure to use message.member in place of user, and you should implement it at the beginning of your code.
module.exports = {
name: 'announce',
description: "announce",
execute(message, args) {
if (!message.member.hasPermisson('KICK_MEMBERS')) // if member doesn't have permissions
return message.channel.send('Insufficient Permissions');
// rest of your code...

Mentioning users in embed

I'm currently making a hug command.
Im trying to make my bot mention the the user that used to command and the one that the user mentioned while using the command, my main problem is the bot sends the '#user has hugged #user' outside of the embed,
here is the code that im using
const messages = ["https://media.tenor.com/images/c6f27ebfd8657a83794329468c27197f/tenor.gif"]
module.exports = {
name: 'embed',
description: "hug embed",
execute(message, args){
const randomMessage = messages[Math.floor(Math.random() * messages.length)]
const hugged = message.mentions.users.first();
const reply = message.reply(`has hugged! <#${hugged.id}>`);
if(!hugged) return message.reply('please mention who you want to hug');
let embeddedHug = new Discord.MessageEmbed()
.setDescription(reply)
.setImage(randomMessage)
message.channel.send(embeddedHug);
}
}
Any suggestions why the bot sends it ouside of the embed?
You are not doing it correctly.
message.reply() is used to send a normal message and automatically mention the author on the beginning of the message.
This is what you want.
const hugged = message.mentions.users.first();
const embedMessage = `<#!${message.author.id}> has hugged <#!${hugged.id}>`;
let embeddedHug = new Discord.MessageEmbed()
.setDescription(embedMessage)
.setImage(randomMessage)
message.channel.send(embeddedHug);

(Discord.js) how too tag the bot itself

okay , hey there.
Im trying too ping/tag the bot itself in Discord.js.
soo when a user ping the bot in a command that it replies with an error message i defined myself.
thats what i have so far :
async run(message, args)
{
let huggeduser = message.mentions.users.first()
let auser = message.author
if(huggeduser == message.author) {
message.channel.send(`${auser} , you cant hug yourself!`)
return;
}
if(client.bot = huggeduser) { //(Note) How too tag the bot as it self like : (huggeduser == <the string too tag the bot>) {
message.channel.send("You cant meeeee hug!")
return;
}
the rest of the code works fine.
just the code-part of the with the (note)
i would love if someone can help me on that. ive been trying it myself for 2 days now.
Thanks.
Use double equal signs for checking equality. Also, checking the entire user objects is inefficient, just check their IDs.
Additionally, based on your error in the comments, and the name of this function, I'm assuming this is in a different file and you have a line like this at the top:
const client = new Discord.Client();
So in this context, client is not your logged-in bot user, it's an empty, not logged in bot that doesn't know who it is. You should get the client from the message object:
async run(message, args)
{
let huggeduser = message.mentions.users.first()
let auser = message.author
if(!huggeduser) return; //message for if no user was mentioned?
if(huggeduser.id == auser.id) {
message.channel.send(`${auser} , you cant hug yourself!`)
return;
} else if(huggeduser.id == message.client.user.id) {
message.channel.send("You cant meeeee hug!")
return;
}
//rest of code

I keep getting an error in discord.js "discord is not defined" OR I get no response from the bot. Not even an error/

I am coding a discord bot using discord.js.
FOR SOME REASON it says Discord not defined error or the bot has no response. Please could you help me? I have never had this error before. Here's the code.
I have include this command in the same main.js file:
if(cmd === `${prefix}help`){
reporthelp = "Report a user. Requires a channel named `reports`to work!";
kickhelp = "Kick a user from the server. Requires a channel named `incidents` to work; you must have the manage messages permission.";
banhelp = "Ban a user from the server. Requires a channel named `incidents` to qork; toy need the BAN MEMBERS permission to use this command!";
warnhelp = "**COMMAND COMING SOON!**";
requiredperms = "**Embed Links, channel named `incidents`; channel named `reports`; channel named `suggestions`; Kick Members, Ban Members, Manage Roles, Manage Members.**"
helpEmbed = new Discord.RichEmbed()
.setDescription(" 💬 **__Help Is Here!__** 💬")
.setColor("#936285")
.addField("**/report #user <reason>**", reporthelp)
.addField("**(COMING SOON)** /warn #user <reason>", warnhelp)
.addField("**/kick #user <reason>**", kickhelp)
.addField("**/ban #user <reason>**", banhelp)
.addField("**/mytag**", "Shows you **your** discoord username#discrim and your user ID. Requires Embed Links permission.")
.addField("**/invite**", "Get a linkto incite meto our server, and an invite link to my suppoer server")
.addField("**/owner**", "see who currently owns the bot")
.addField("**/git**", "**SOURCE CODE AVAILIBLE SOON**")
.addField("**/token**", "View the bot's super secret bot token!")
.addField("**/serverinfo**", "displays some basic server information!")
.addField("**/botinfo**", "displays basic bot information!")
.addField("**/ping**", "Get the bot to respond with `pong` ")
.addField("**/hosting**", "Bot finds a good website for bot/web hosting")
.addField("**/quotes**", "bot responds with some lovely quotes!")
.addField("**__Required Permissions__**", requiredperms)
// .addField("**COMING SOON!**/suggest <suggestion>", "suggest something. Requires channel named `suggestions`")
.setTimestamp()
.setFooter("Use /invite to invite me to your server!")
return message.channel.send({embed: helpEmbed});
}
This is how I've defined everything:
const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is active in ${bot.guilds.size} servers!`);
bot.user.setActivity("rewriteing main.js...", {type: "WATCHING"});
//bot.user.setGame("Lookin' out for ya!");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
const prefix = botconfig.prefix;
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
const bicon = bot.user.displayAvatarURL;
I either get no response/error, or I get the error discord is not defined.
I'm also very new here, sorry If I didn't ask a question clearly...
The code is correct, but I had redfined discord in a different part of the file....
my advice would be to alays read the code over again!

How do I handle user response (facebook) chat bot?

Trying to create a facebook chatbot with NodeJS.
The problem is that I can easily handle user response to "button" messages with few choices to pick but can't handle input from simple text messages ("what is your favourite color?").
The conversation should be as follows :
Bot : Welcome, I have some questions for you.
What is your phone number?
User :
Bot : How old are you?
User :
etc.
So what would be the way out to make this flow of question->answer possible?
My code so far:
let messaging_events = req.body.entry[0].messaging;
for (let i = 0; i < messaging_events.length; i++) {
let event = messaging_events[i];
if (event.message && event.message.text) {
let text = event.message.text;
let textid = event.message.mid;
}
}
You can use this module facebook-chat-api.
Or read it to learn how to create it.
And are you using facebook-graph-api or login with NodeJs ?

Resources