Discord.js and http listener with GET request - bots

I have a windows application that receives http GET requests. for example, send a message to a user or send a message to a chat channel. But I can't create a voice or text channel on the server by means Discord.js. I turn to the forum from despair. Please help
So the system is implemented:
Windows App (for Users) <==> Windows Server for App <==> Discord Bot (Server) <==> MYSQL
For example, send a message:
if (req.params.type === 'sendMessage')
{
channelName = req.params.channel;
message = req.params.message;
channel = bot.channels.find('name', channelName);
channel.send(message);
}

The problem is solved. Maybe someone will help. Topic closed.
bot.rest.methods.createChannel('424511917596606464' ,nameChannel, "text", 0, 0); (snowflake server, nameChannel, voice or text or category, overwrites, reason)
const bot = new Discord.Client();

Related

How To Send A Discord.JS Startup Message To All Servers

I wanted to inquire on something I’ve been trying to do recently. I have a Discord.JS bot, and it’s pretty public (130+ servers), and I want it to send a message to any channel in every single server it’s in, when the bot starts up, the purpose is to create a “New Update” notification in one of the channels.
Please do not plan on doing this, as this will get you rate limited really quickly.
This is kind of possible. There is a problem, there is no default guild channel, so you cannot get their "main" channel just by their guild object. If you would want to do that you, would need them to select their channel and store that ID somewhere.
This is a simple solution, where you loop through every guild of your Discord client, and send some channel a message. You don't know what channel with this solution specifically, but you will send some channel a message if it is not a voice channel.
const Discord = require("discord.js");
require("dotenv").config();
// Creating our Client
const client = new Discord.Client();
// Event listener: when the bot is ready
client.on("ready", () => {
// Looping through every guild the bot is in
client.guilds.cache.forEach((guild) => {
// Getting one of their channels
let channel = guild.channels.cache.array()[2];
// Sending the channel a message
channel.send("Hey");
});
});
client.login(process.env.DISCORD_BOT_TOKEN);

How to get all non bot users in discord js using a discord bot in nodejs

I have created a discord bot by taking reference from this digital ocean link.
Now I can send message to any channel using the bot but my requirement is to send dm to user of that server.
For that I have tried many SO answers and followed other links, but all the solutions end up to be same.
I have tried this two way to get the users of a guild and send dm to any one selected user.
1st way - Get all users of guild (server)
const client_notification = new Discord.Client();
client_notification.on('ready', () => {
console.log("Notification manager ready");
let guild = client_notification.guilds.cache.get("Server ID");
guild.members.cache.forEach(member => console.log("===>>>", member.user.username));
});
client_notification.login("login");
Output
Notification manager ready
===>>> discord notification
By this way it only returns me the bot name itself. Although the membersCount is 6.
2nd way - send dm to user directly (server)
client.users.cache.get('<id>').send('<message>');
It gives me undefined in output.
My configs,
Node version: 10.16.3
discord.js version: 12.5.1
My question is how to get all the guild members in discord.js?
Discord added privileged gateway intents recently. So to fetch all member data you need to enable that in the developer portal. After that you need to fetch all the members available, for that we can use the fetchAllMembers client option, and then we need to filter out bot users, so that we don't message them.
const client_notification = new Discord.Client({fetchAllMembers:true}); //Fetches all members available on startup.
client_notification.on('ready', () => {
console.log("Notification manager ready");
let guild = client_notification.guilds.cache.get("Server ID");
guild.members.cache.filter(member => !member.user.bot).forEach(member => console.log("===>>>", member.user.username));
});
client_notification.login("login");
The .filter() method filters out all the bots and gives only the real users.
You should avoid using fetchAllMembers when your bot gets larger though, as it could slow down your bot and use lots of memory.
I think the problem is related to updating the bot policy for discord. Do you have this checkbox checked in the bot settings?
https://discord.com/developers/applications
Some info about client.users.cache:
Its a cache collection, so if you restart bot, or bot never handle user message or actions before, this collection will be empty. Better use guild.members.cache.get('')

Telegram: Cannot send message/photo into a channel with Telegraf (NodeJs)

I would send a message on telegram channel with telegraf. I'v einvited the bot and put him admin.
I've tested with this code:
bot.on('text', (ctx) => {
// Explicit usage
ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)
// Using context shortcut
// ctx.reply(`Hello ${ctx.state.role}`)
})
bot.launch();
But it replies only if i wrote on private.
So why it doesn't work on a channel?
Than how can i send a message in that channel without a command? (For example with and interval?
I i try this one:
bot.use((ctx) => {
console.log(ctx.message)
})
when i use the bot on private chat (with him) it returns all the message data. On the channel i receive undefined
In your case CTX have current chat info, if you want to send message to channel provide correct id as documented for Telegraf sendMessage:
telegram.sendMessage(process.env.TELEGRAM_CHANNEL, ctx.message.text);
I am using a bot for a public channel, so in my case it's:
TELEGRAM_CHANNEL=#MY_PUBLIC_CHANNEL_NAME
The channel name is available in channel info settings t.me/MY_PUBLIC_CHANNEL_NAME

How can I get my bot to post a message to a Microsoft Teams channel?

I have a bot that is identical to the one demonstrated in the docs quickstart. It repeats back whatever the user says (for now).
It is currently running locally and exposed with ngrok. I've registered the bot with the Microsoft Bot Framework.
I have configured the Microsoft Teams channel in the Microsoft Bot Framework, and I've sideloaded my bot into Teams. My bot can receive messages from Teams users.
At present, the bot just repeats whatever it receives back to the user, but what I want it to do is post to a Microsoft Teams channel. I want it to post to a Teams channel - not a user - without being prompted first by a user. So for example given a certain condition (eg. triggered by some event such as time of day, a pull request, etc.) it posts a message in a channel.
I've read the documentation about sending proactive messages, and I gather that in order to send a message to a teams channel, the bot needs to know the "address" of the user. This information is stored in the session.message.address object, and it gets this from the current conversation. However, in my case I don't have a 'current conservation', because I don't want to just respond to a user, I want to post in a channel proactively.
So, how do I permanently set the necessary credentials/address/session-data for the Teams channel?
Things I've looked into:
Webhooks. I've configured a webhook in my Teams channel, and I can send it a message easily enough (using the webhook url) using curl. So I can send the Teams channel a simple message with just a url (no authentication required), but I'm not sure how I'd get this url into my bot.
How do we maintain different session for different users in Microsoft Bot Framework? I'm not sure that the answer here answers my question. My problem is that the bot is initiating the 'conversation', not a Teams user, so I need to be able to set the session data myself so the bot knows where to go.
App.js:
require('dotenv').config();
var restify = require('restify');
var builder = require('botbuilder');
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
// Listen for messages from users
server.post('/api/messages', connector.listen());
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
session.send("You said: %s", session.message.text);
});
For anyone who is wondering about the same for c#, here is the solution that worked for me:
var channelData = context.Activity.GetChannelData<TeamsChannelData>();
var message = Activity.CreateMessageActivity();
message.Text = "Hello World";
var conversationParameters = new ConversationParameters
{
IsGroup = true,
ChannelData = new TeamsChannelData
{
Channel = new ChannelInfo(channelData.Channel.Id),
},
Activity = (Activity) message
};
var connectorClient = new ConnectorClient(new Uri(activity.ServiceUrl));
var response = await
connectorClient.Conversations.CreateConversationAsync(conversationParameters);
Note: If you are calling this outside Bot's controller code then you need to call TrustServiceUrl on serviceUrl as shown here:
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl, DateTime.MaxValue);
var connectorClient = new ConnectorClient(new Uri(serviceUrl));
Source of answer: https://github.com/OfficeDev/BotBuilder-MicrosoftTeams/issues/162
It is definitely possible. We call these proactive messages and it’s possible to proactively message both users and channels.
For the latter, see the sample at https://github.com/OfficeDev/microsoft-teams-sample-complete-node, specifically this file, ProactiveMsgToChannelDialog.ts.
To send proactive messages to channels, you need to use the Microsoft Teams SDK (as these samples do).
Last but not least, you need to add the bot to a team in order to send a message to one of the channels in the team, which requires a manifest.
Hope this works for you.. below code proactively sends the message to session before initiating the chat.
bot.on('conversationUpdate', function (message) {
if (message.membersAdded[0].id === message.address.bot.id) {
var reply = new builder.Message()
.address(message.address)
.text("Hello"");
bot.send(reply);
}
});

Creating a Socket IO channels from client side

I'm new to Nodejs and Socketio. I want to do something like the following.
-> Create a socket.io/node.js server that listens to channels specified by the web browser.
-> server side script pushes messeges to specific channels.
(I already have a server created and here is the code. This just sends out two messeges. action and messege to all the connected clients)
//start code
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, url = require('url')
app.listen(8080);
function handler (req, res) {
// parse URL
var requestURL = url.parse(req.url, true);
// if there is a message, send it
if(requestURL.query.message)
sendMessage(decodeURI(requestURL.query.action), decodeURI(requestURL.query.message));
// end the response
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("");
}
function sendMessage(action, message) {
io.sockets.emit('notification', {'action': action, 'message' : message});
}
So basically Socket.io server doesn't have any channels defined inside them. But they are defined by the client (js in browser) and messeges are sent to the specific channels by a server side script (like php using cURL)
Sorry if this questions has been asked before, I did search and couldnt find anything helpful.
I am bit confused about your question. By channels, do you mean socket.io rooms?
https://github.com/LearnBoost/socket.io/wiki/Rooms
Rooms are groups of clients and it is possible to send message to all clients in room by using following command:
io.sockets.in('room').emit('event_name', data)
It is important to realize that rooms are server side thing. So, if you want to send message to a room from client, you must send message (or request) to server and pass room name.
Also, it is bit unusual that your handler function is exposed as HTTP endpoint. If your clients already have socket.io connections, than it is easier to send it as socket.io message.
If this does not answer you question, can you post also your client side code? Maybe it will help to understand me what are you trying to achieve.

Resources