help please, I am writing a telegram bot for feedback, at the moment it works in a private chat (i.e. the user writes to the bot - I answer reply the bot via reply and the user receives SMS from the bot), but does not work in the group chat( in a group I can see the user's messages, but I can't reply to the user through reply). it is necessary that any user from the group can reply to the user's message
const bot = new Telegraf(token, {});
let replyText = {
'helloAdmin': '...',
'helloUser': '...',
'replyWrong': '....'
};
let isAdmin = userId => {
return userId === admin;
};
let forwardToAdmin = ctx => {
if (isAdmin(ctx.message.from.id)) {
ctx.reply(replyText.replyWrong);
} else {
ctx.forwardMessage(admin, ctx.from.id, ctx.message.id);
}
};
bot.start(ctx => {
ctx.reply(isAdmin(ctx.message.from.id)
? replyText.helloAdmin
: replyText.helloUser);
});
bot.on('message', ctx => {
if (ctx.message.reply_to_message && ctx.message.reply_to_message.forward_from && isAdmin(ctx.message.from.id)) {
ctx.telegram.sendCopy(ctx.message.reply_to_message.forward_from.id, ctx.message);
} else {
forwardToAdmin(ctx);
}
});
bot.launch();
there is a getChatAdministrators method (https://core.telegram.org/bots/api#getchatadministrators), I guess you can use it to get Admins of the group and check if one of them is replied. In that case forward it back to user
Related
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})
I am working on creating a telegram bot, I want to make an anti-spam system, that is, when a person presses a button too many times, the bot will freeze for him for a certain number of seconds, it is possible to write a message about blocking. I just started learning JavaScript.
I use node-telegram-bot-api.
import {
bot
} from '../token.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
return bot.sendMessage(chatId, 'error');
});
}
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use: You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I am working on creating a telegram bot, I want to make an anti-spam system, that is, when a person presses a button too many times, the bot will freeze for him for a certain number of seconds, it is possible to write a message about blocking. People in other matters do not help me.
import {
bot
} from '../token.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
return bot.sendMessage(chatId, 'error');
});
}
Do you use telegraf as telegram module ? If yes, you can kick users from channels or groups.
here is a little piece that i made for you :)
you can apply it to anything ^_^
var tps = 0;
var allowpassage = false;
var detectspamon = document;
c = function() {
setTimeout(()=>{
console.log("got clicks:",tps);
if (tps==0) {console.log("no clicking detected");}
else if (tps==1) {console.log("success");allowpassage=true;}
else {console.log("too many clicks per second");}
tps=0;
console.log("setting clicks to 0");
},500);
}
detectspamon.onclick = () => {tps++;console.log(tps);c(tps);}
I'm trying to do a simple login to Azure AD using the MSAL for JavaScript v2.0 library. We want users to be able to authenticate into our site with their work Microsoft accounts. All I need to do is be able to authenticate/login the user via Microsoft, and if they can login via their work Microsoft account, then they're granted access to our site.
I'm using the Javascript library and have followed the code from the Github page and while the login prompt is coming up, afterwards I have no idea how to check if the user is signed in.
Here's the code I'm using, which is basically what's in the sample code from Github:
<script type="text/javascript" src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js"></script>
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "[ClientID goes here]",
authority: "https://login.microsoftonline.com/[tenant ID]",
knownAuthorities: ["login.microsoftonline.com"],
protocolMode: "OIDC",
redirectUri: "[page on our site that doesn't have MSAL auth, listed in Azure Reply URLs]"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: true, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["User.Read"]
};
const silentRequest = {
scopes: ["openid", "profile", "User.Read"]
};
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;
let signInType;
let accountId = "";
let credType = "";
// Create the main myMSALObj instance
const myMSALObj = new msal.PublicClientApplication(msalConfig);
// Register Callbacks for Redirect flow
myMSALObj.handleRedirectPromise().then(handleResponse).catch((error) => {
console.log(error);
});
function handleResponse(resp) {
alert("beginning handleResponse");
if (resp !== null) {
accountId = resp.account.homeAccountId;
credType = resp.account.credentialType;
myMSALObj.setActiveAccount(resp.account);
alert("response not null (already auth), accountId: " + accountId + ", credType: " + credType);
}
else {
const currentAccounts = myMSALObj.getAllAccounts();
if (!currentAccounts || currentAccounts.length < 1) {
alert("currentAccounts null/empty, going to signIn");
signIn("loginRedirect");
//return;
}
else if (currentAccounts.length > 1) {
// add choose account code here
alert("currentAccounts has multiple");
}
else if (currentAccounts.length === 1) {
const activeAccount = currentAccounts[0];
myMSALObj.setActiveAccount(activeAccount);
accountId = activeAccount.homeAccountId;
credType = activeAccount.credentialType;
alert("currentAccounts == 1; accountId: " + accountId + ", credType: " + credType);
}
}
}
async function signIn(method) {
signInType = isIE ? "loginRedirect" : method;
if (signInType === "loginPopup") {
return myMSALObj.loginPopup(loginRequest).then(handleResponse).catch(function (error) {
console.log(error);
});
}
else if (signInType === "loginRedirect") {
return myMSALObj.loginRedirect(loginRequest);
}
}
function signOut() {
const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId)
};
myMSALObj.logoutRedirect(logoutRequest);
}
async function getTokenPopup(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
console.log("acquiring token using popup");
return myMSALObj.acquireTokenPopup(request).catch(error => {
console.error(error);
});
}
else {
console.error(error);
}
});
}
// This function can be removed if you do not need to support IE
async function getTokenRedirect(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
console.log("acquiring token using redirect");
myMSALObj.acquireTokenRedirect(request);
}
else {
console.error(error);
}
});
}
So what happens upon going to this page is I get the two alerts saying "beginning handleResponse" and then "currentAccounts null/empty, going to signIn."
Then I'm redirected to MS sign-in page which I do with my work MS account. This succeeds.
I'm then redirected to the site I have listed in Azure Reply URLs, another page on our site that isn't secure and has no Azure login code.
The problem is I have no idea where to check that the user is signed in. If I try and check immediately after the signIn("loginRedirect") call in the handleResponse() function on the first page, the code never gets hit apparently. If I try and check on the page I'm redirected to, by instantiating the MSAL object and calling getAllAccounts(), this returns null.
It seems maybe on the page I'm redirected to I could call the ssoSilent() function (seems like this can check if user is authenicated?), but this requires a username/AccountId parameter. Well I don't frickin know this if a user hasn't (possibly) been authenticated yet! I don't really understand that.
So I don't know. It's probably something stupid I'm doing but I'm a pretty basic JavaScript person and am pretty much a total noob with authenication stuff. Any help would be epic.
const Discord = require("discord.js"),
bot = new Discord.Client();
let pre = "?"
bot.on("message", async msg => {
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var prisonerRole = msg.guild.roles.find("name", "Prisoner");
let command = msgArray[0];
if (command == `${pre}roll`) {
if (!msg.member.roles.has(prisonerRole.id)) {
roll = Math.floor(Math.random()*6)+1;
msg.reply(`You rolled a ${roll}`)
} else {
msg.reply(`HaHa NOOB, you're in prison you don't get priveleges!`)
}
}
if (command == `${pre}kick`) {
var leaderRole = msg.guild.roles.find("name", "LEADER");
var co_leaderRole = msg.guild.roles.find("name", "CO-LEADER");
if (msg.member.roles.has(leaderRole.id) ||
msg.member.roles.has(co_leaderRole.id)) {
var kickUser = msg.guild.member(msg.mentions.users.first());
var kickReason = args.join(" ").slice(22);
msg.guild.member(kickUser).kick();
msg.channel.send(`${msg.author} has kicked ${kickUser}\nReason: ${kickReason}`);
} else {
return msg.reply("Ya pleb, you can't kick people!");
}
}
})
bot.login("token").then(function() {
console.log('Good!')
}, function(err) {
console.log('Still good, as long as the process now exits.')
bot.destroy()
})
Everything works except actually kicking the person. The message sends nut it doesn't kick people. For example, when I type in ?kick #BobNuggets#4576 inactive, it says
#rishabhase has kicked #BobNuggets
Reason: inactive
But it doesn't actually kick the user, which is weird, can you help me?
Change
msg.guild.member(kickUser).kick();
to
kickUser.kick();
also, make sure the bot is elevated in hierarchy
Use kickUser.kick();
I recommend using a command handler to neaten up your code. You don't want all your commands in one .js file.
Try something like this for the Ban command itself. I use this for my Bot:
client.on("message", (message) => {
if (message.content.startsWith("!ban")) {
if(!message.member.roles.find("name", "Role that can use this bot"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// ban
member.ban().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully banned :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
That should work, set the role you want to use it (cAsE sEnSiTiVe) and change !ban to whatever you feel like using. If you change all "ban"s in this to kick, it will have the same effect. If this helped you, mark this as the answer so others can find it, if not, keep looking :)