How to check telegram group invitation link parameters on new_chat_members - node.js

I have telegram bot which is added to the group and is listening on everything what is going on on the group. There is a command /invite implemented which displays invitation link to the group (not to the bot but to the group). This link contains parameter refUserId so I can get it later and count how many people has been invited by particular members of the group. This is what I was going to achieve but looks like there is no way to retrieve invitation link parameters on the new_chat_members event.
Here is a piece of code I want to retrieve the param
bot.on('new_chat_members', ctx => {
// retrieve refUserId param here
})
I'm open to any suggestion and will be more than grateful to hear some other solutions.
Here is bigger picture in case that's needed
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply(`${Constants.msg.welcome(ctx.from.first_name)}`))
bot.command('invite', ctx => {
// reply with invitation link like this:
// t.me/myGroupIdWillBeHere?refUserId=${ctx.from.id}
})
bot.on('new_chat_members', ctx => {
// retrieve refUserId param here
})
bot.launch()

Related

(discord.js v13) If channel exists

I'm making a ticketing system with buttons. I trying to if user opened a ticket, user can't open a new ticket. Im tried some code:
//ticket channel is created with **"help: " + interaction.user.username** name
if (interaction.guild.channels.fetch('channel name'))
//working with only id
if (interaction.guild.channels.cache.get(c=>c.name==='channel name'))
//reacted nothing
The discord.js channels cache is a Discord.Collection of values, meaning that it is a JS map with some extra quality of life methods added by Discord.js. Discord Collections are keyed using the snowflake id with the value being whatever object is being stored with that id (in this case the channel you want). This means that the method fetch on the collection of channels can always only be passed an ID as stated here in the docs. This would also mean that the Map.get() method you try to use in the second attempt will not return anything as the channel is not keyed by its name, its keyed by a snowflake id.
You can use a piece of code like this one I used in a discord moderation bot to find and return a channel by name if it exists in the cache.
/**
* Get the log channel for the provided guild.
* #param {Discord.Guild} guild The guild to get the log channel for.
*/
#getLogChannel = (guild) => {
const guildLogChannel = guild.channels.cache
.find(channel => channel.name === 'guild-logs');
if (!guildLogChannel) return false;
return guildLogChannel;
}
If the channel has not yet been cached you have no other option than to pass that channel into the interaction as an option, fetch the channel by its snowflake id, or fetch all channels for all guilds the bot is in inside your client.on('ready', () => {}) handler. The last option is what I chose to do for the bot that the above code snippet is taken from.

How do I exclude specific users from a discord server dm bot

I have a bot for a discord server that sends a dm to all of my server's members.
(The code is written in node.js.)
Reading the code, I cant figure out how to add an exception to skip over certain users in my server.
What would that line of code look like, would it need to interact with some other function in my bot's code?
I can provide you the code if that is necessary to understand my question.
// Getting the guild by id.
const Guild = client.guilds.cache.get("GuildID");
/*
| Since Guild.members.cache is a Collection, you can use filter() to exclude certain members.
*/
const ExcludedMembers = ["UserID", "UserID", "UserID"];
const Members = Guild.members.cache.filter(member => !ExcludedMembers.includes(member.id));
/*
| The Members constant contains all the members in the guild, except for the ExcludedMembers.
| Now you can look through Members and send the message.
*/
Members.forEach((member, i) => {
setTimeout(() => {
member.send(`Hello, this is ${client.user.tag}!`).catch(e => console.error(`Couldn't send the message to ${member.user.tag}!`))
}, i * 1000)
});

How to forward message from channel to the groups on telegram bot?

im trying to implement my bot a function. Function that if the channel write any message it will be forwarded to the groups where the bot already is.
Trying to use scope method that worked like a charm on welcome message when new user joined the group.
//index.js
const Telegram = require('telegram-node-bot'),
tg = new Telegram.Telegram('MYAPI', {
workers: 1
});
const ForwardController = require('./controllers/forward')
tg.router.when(new Telegram.TextCommand('/info', 'infoCommand'), new InfoController())
.otherwise(new ForwardController());
//forward.js
const Telegram = require('telegram-node-bot');
class ForwardController extends Telegram.TelegramBaseController {
handle(scope) {
if ('channel' == scope.message.chat._type) {
scope.api.forwardMessage(scope.message._chat._id, _forwardFromChat._text);
}
}
}
module.exports = ForwardController;
I tried many combinations but the message is never forwarded... The bot is already administrator on the channel and is also putted in the groups. (Have also private message opened with bot so i think it should forward also there)
Take a look at the API reference for the library, the documentation page appears to be down so Github is your friend.
The forwardMessage call you are making has incorrect arguments and is accessing the private class variables. It is also returning a promise so you should await the promise or chain a .then to it. You can use the class methods on the Scope instance itself.
It should be more like:
// using async/await - note the containing function must be async for this approach
const result = await forwardMessage(<id of chat here>, scope.message().id());
// or to chain a .then
forwardMessage(<id of chat here>, scope.message().id())
.then(result => /* do something with result */)
.catch(err => /* handle the error */);
This will use the Scopes instance method and handle sending the id of the current chat for you, all you need is the id of the chat you want to send the message to and then replace the <id of chat here> with that id.

issue with creating role and channel automatically from private message with bot

Not sure how the create channel and create role isn't working inside the following code, towards the bottom. (EDIT: Nothing is sent to the console and nothing happens regardng the code. It is like it is entirely ignored.) This is a snippet from code that User A challenges User B. User B is messaged, alerting them that a challenge has been issued to them via a Private Message. If the challenge is accepted, I want the bot to 1)Make a role specifically for User A and User B named "User A vs User B" 2) take User A and User B and put them both into that new role and 3) Make a battlefield named "User A vs User B" inside a specific category inside the server the bot is on.
I am unsure if the problem lies in how the bot is trying to make the role and channel in a sever while the bot is talking to the user in a private message instead of on the server. I thought putting the "server" variable as the server ID would help but it doesn't seem to do anything after the accept message.
// Awaits reply from user
if (message.channel.id === '541736552582086656') return target.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
.then((newmsg) => {
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 150000,
errors: ['time'],
}).then((collected) => {
// Grabs the first (and only) message from the collection.
const reply = collected.first();
if (reply.content === 'accept'){
reply.channel.send(`You have ***accepted *** the challenge from ${challenger}. Please wait while your battlefield is made...`);
message.author.send(`${target} has accepted your challenge! Please wait while the channel is made for your brawl...`)
/// Problems start here
function createChannel(message){
var server = "SERVER ID";
var name = `${target} vs ${challenger}`;
message.guild.createRole({
role: {
name: `${target} vs ${challenger}`,
color: "#00fffa",
permissions: [] }
}).then(role => {
target.addRole(role, name)
challenger.addRole(role, name)
.catch(error => client.catch(error))
}).catch(error => client.catch(error))
server.createChannel(Name, name).then(
(channel) => {
channel.setParent("CATEGORY ID")
})
} // problems end here
} else if (reply.content === 'deny') {
reply.channel.send("You have ***denied *** the challenge.")
} else {
reply.channel.send("Your response wasn't valid.");
}
})
})
}
I have been wondering if I need to go about making the channel and role in a different way since it is trying to be made from a private message and not inside the server..
Thanks for any and all help! I also apologize if I'm using stack overflow too much for problems like this... You guys are great at helping me see different ways to do things and what I'm doing wrong, so I am learning, but I don't want to feel like I'm abusing it too much.
I think the problem is the fact that you create a function called createChannel with the code to create a rol and channel, but you never call said function.
You can either call the function after you've declared it or (which is in my opinion better) you can remove the following lines
function createChannel(message){
} // problems end here

Private messaging a user

I am currently using the discord.js library and node.js to make a discord bot with one function - private messaging people.
I would like it so that when a user says something like "/talkto #bob#2301" in a channel, the bot PMs #bob#2301 with a message.
So what I would like to know is... how do I make the bot message a specific user (all I know currently is how to message the author of '/talkto'), and how do I make it so that the bot can find the user it needs to message within the command. (So that /talkto #ryan messages ryan, and /talkto #daniel messages daniel, etc.)
My current (incorrect code) is this:
client.on('message', (message) => {
if(message.content == '/talkto') {
if(messagementions.users) { //It needs to find a user mention in the message
message.author.send('Hello!'); //It needs to send this message to the mentioned user
}
}
I've read the documentation but I find it hard to understand, I would appreciate any help!
The send method can be found in a User object.. hence why you can use message.author.send... message.author refers to the user object of the person sending the message. All you need to do is instead, send to the specified user. Also, using if(message.content == "/talkto") means that its only going to run IF the whole message is /talkto. Meaning, you can't have /talkto #me. Use message.content.startsWith().
client.on('message', (message) => {
if(message.content.startsWith("/talkto")) {
let messageToSend = message.content.split(" ").slice(2).join(" ");
let userToSend = message.mentions.users.first();
//sending the message
userToSend.send(messagToSend);
}
}
Example use:
/talkto #wright Hello there this is a dm!

Resources