How to forward message from channel to the groups on telegram bot? - node.js

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.

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.

Direct Messaging custom slack bot built on node.js

I have built a slack bot using the slack/bots apis in node.js: https://slack.dev/bolt-js/tutorial/getting-started
Currently, it is working fine when I type <bot> help in a channel I have set up for using webhooks. I am trying to run those same commands in a DM with the bot using the app.event('app_mention',...) method but it is not working. its like the message doesn't register in a DM with the bot for some reason but it works in a public channel. code snippet below:
app.event('app_mention', async ({ event, client}) => {
console.log(event);
const text = event.text;
const parentMessageId = event.ts;
const eventChannel = event.channel;
if (text.includes("help")) {
console.log(event);
try {
await client.chat.postMessage({
channel: eventChannel,
text: helpMessage,
thread_ts: parentMessageId
});
} catch (err) {
console.error(err);
}
I should have permissions set up correctly as well. I basically have all the permissions that I can add for the bot
The documentation of the app_mention api specifically mentions that this event does not work with DMs.
Messages sent to your app in direct message conversations are not
dispatched via app_mention, whether the app is explicitly mentioned or
otherwise. Subscribe to message.im events to receive messages directed
to your bot user in direct message conversations.
Check here : https://api.slack.com/events/app_mention

How to check telegram group invitation link parameters on new_chat_members

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()

Sending message to specific channel, not working

Having trouble sending a bot message on a specific channel. I very simply want to have the bot send a message to #general when it activates, to let everyone know it's working again.
In the bot.on function, I've tried the classic client.channels.get().send(), but the error messages I'm getting show that it thinks client is undefined. (It says "cannot read property 'channels' of undefined")
bot.on('ready', client => {
console.log("MACsim online")
client.channels.get('#general').send("#here");
})
The bot crashes immediately, saying: Cannot read property 'channels' of undefined
The ready event doesn't pass any client parameter.
To get a channel by name use collection.find():
client.channels.find(channel => channel.name == "channel name here");
To get a channel by ID you can simply do collection.get("ID") because the channels are mapped by their IDs.
client.channels.get("channel_id");
Here is an example I made for you:
const Discord = require("discord.js");
const Client = new Discord.Client();
Client.on("ready", () => {
let Channel = Client.channels.find(channel => channel.name == "my_channel");
Channel.send("The bot is ready!");
});
Client.login("TOKEN");
You need to get the guild / server by ID, and then the channel by ID, so your code will be something like :
const discordjs = require("discord.js");
const client = new discordjs.Client();
bot.on('ready', client => {
console.log("MACsim online")
client.guilds.get("1836402401348").channels.get('199993777289').send("#here");
})
Edit : added client call
The ready event does not pass a parameter. To gain the bot's client, simply use the variable that you assigned when you created the client.
From your code, it looks like the bot variable, where you did const bot = new Discord.Client();.
From there, using the bot (which is the bot's client), you can access the channels property!

Messaging a user a bot does not know

I am using the Slack RTM node client and having a bit of an issue with DM's. Say a user joins the channel who has never DM'ed the bot before, the user types a command in the channel that the bot usually will respond to and by default the bot responds in a private message to the user. However, the bot cannot do this because the dataStore does not contain any DM data for this user. Code sample below...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
user = rtm.getUserById(message.user);
console.log(user); // It gets the user object fine
dm = rtm.getDMByName(user.name);
console.log(dm); // This is always undefined unless the user has DM'ed the bot previously
});
Is there a way around this? I can't seem to find anything in the docs or code to suggest there might be.
You can use the im.open method of the web API. Here's roughly how you'd do it with #slack/client (untested, apologies in advance!):
var webClient = new WebClient(token);
...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
var dm = rtm.getDMById(message.user);
if (dm) {
console.log(`Already open IM: ${dm}`);
// send a message or whatever you want to do here
} else {
webClient.im.open(message.user, function (err, result) {
var dm = result.channel.id;
console.log(`Newly opened IM: ${dm}`);
// send a message or whatever you want to do here
});
}
});

Resources