Discordie Channel Switching - discord

So I have your average Discordie node.js code, but I have no idea how to make this send messages in other channels.
The idea is, when a user requests something, it will go into a channel called requests.
var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
//make this send in a request channel.
e.message.channel.sendMessage("pong");
});

var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
var channels = e.message.channel.guild.textChannels;
var channel = null;
for(int i = 0; i < channels.length; i++) {
channel = channels[i];
if(channel.name == "YOUR CHANNEL NAME")
break;
}
channel.sendMessage("pong");
});

Related

System.Threading.Timer: A second operation was started on this context with

I have Console Application on .NET 5 which is Discord Bot.
While start the application i have the problem with this:
System.InvalidOperationException: A second operation was started on
this context before a previous operation completed. This is usually
caused by different threads concurrently using the same instance of
DbContext. For more information on how to avoid threading issues with
DbContext
And this is happens in Timer
This is in constructor:
_approveTimer = new Timer(async delegate
{
await CheckApproveAsync();
}, null, TimeSpan.Zero,
TimeSpan.FromSeconds(30));
public async Task CheckApproveAsync()
{
var pendingUsers = await _pendingUsers.GetAllAsync();
if (pendingUsers is null || !pendingUsers.Any())
return;
Program.Log.Debug($"Checking {pendingUsers.Count} pending users...");
foreach (var user in pendingUsers)
{
var expired = DateTime.UtcNow > user.ExpirationTime;
if (!expired) continue;
await _pendingUsers.DeleteWithDetachAsync(user);
IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
try
{
var msg = await _messageService.GetMessageAsync("register-pending-expired", new FormatData(user.UserId));
await sgUser.SendIonicMessageAsync(msg);
}
catch (Exception ex)
{
await _serverHelper.SendLogAsync(_mainGuildId, "Error", $"{nameof(CheckApproveAsync)} - {ex.Message}");
}
}
var usersValidated = 0;
foreach (var user in pendingUsers)
{
RequestResult codeResult;
string code;
try
{
(codeResult, code) = await GetThirdPartyCodeByEncryptedSummonerIdAsync(user.Region, user.SummonerId);
}
catch (Exception)
{
continue;
}
if (code is null || codeResult != RequestResult.Success)
continue;
var sanitizedCode = new string(code.Where(char.IsLetterOrDigit).ToArray());
if (sanitizedCode != user.ConfirmationCode)
continue;
var (requestResult, summoner) = await GetSummonerByEncryptedPuuIdAsync(user.Region, user.PlayerUUID);
if (requestResult != RequestResult.Success)
{
await _pendingUsers.DeleteWithDetachAsync(user);
continue;
}
var (rankResult, rankData) = await GetLeaguePositionsByEncryptedSummonerIdAsync(user.Region, summoner.Id);
var soloqRank = GetRankModelFromEntry(rankData.FirstOrDefault(x => x.QueueType == "RANKED_SOLO_5x5"));
var summonerIcon = GetSummonerIconUrlById(summoner.ProfileIconId);
var lolData = new LeagueData
{
UserId = user.UserId,
SummonerRegion = user.Region,
PlayerUUID = summoner.Puuid,
AccountId = summoner.AccountId,
SummonerId = summoner.Id,
SummonerName = summoner.Name,
SummonerIcon = summonerIcon,
SummonerLevel = summoner.SummonerLevel,
SummonerRank = $"{soloqRank.Tier} {soloqRank.Rank}"
};
_ = IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
await AssignRoleFromRankAsync(sgUser, soloqRank.Tier);
var data = await _leagueRepository.GetByIdAsync(user.UserId);
if (data == null)
{
await _leagueRepository.AddAsync(lolData);
}
usersValidated++;
user.SummonerName = lolData.SummonerName;
await PostValidateAsync(user);
}
Program.Log.Information($"{usersValidated} users validated.");
}
I read that it can be problem that if some method is not awaited, but i've checked it's all awaited. Which suggestions about this?

Avoid message repeating?

I need some help here I have a code that shows a message being updated per 2 seconds but I want a single message that replaces itself.
let channel = guild.channels.find(channel => channel.name === guilds[guild.id].digitchan);
let channel2 = guild.channels.find(channel => channel.name === guilds[guild.id].countdownchan);
if (channel && channel2) {
channel.send(embed);
scrims[guild.id] = {
timer: setTimeout(function() {
channel2.join().then(connection => {
const dispatcher = connection.playFile('./Audio/test.mp3');
console.log('dispatcher');
console.log(dispatcher == null);
dispatcher.on('end', () => {
channel2.leave();
const embed2 = new RichEmbed()
.setColor(0xc1d9ff)
.addField("message x", false);
channel.send(embed2);
scrims[guild.id].codes = true;
scrims[guild.id].codedata = {};
scrims[guild.id].playerinterval = setInterval(function() {
const embed4 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "and more";
return false;
};
})
embed4.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed4);
}, 2000);
scrims[guild.id].timer2 = setTimeout(function() {
scrims[guild.id].codes = false;
clearInterval(scrims[guild.id].playerinterval);
const embed3 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "y mas..";
return false;
};
})
embed3.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed3);
}, 1 * 60000);
});
});
}, time * 60000);
};
};
This is the discord action:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes: 3c5
Codes: 3c5
So could be some kind of message deleting before sending the same message updated again, please let me know how to do it or some kind of code changing.
Just use message.edit() to edit the message.
message.edit() on discord.js docs

xmpp message not send to selected friend

I am working in mean stack application and now I required to make chatting module using the XMPP protocol.
I am new with XMPP,
I have used "node-xmpp-server" and "node-xmpp-client" in node js
and "Strophe.js" in angular js.
My code is as below:
app.js (server side file)
"use strict";
var express = require("express");
var https = require('https');
var http = require("http");
var fs = require('fs');
var app = express();
var xmppClient = require('node-xmpp-client');
var xmppServer = require('node-xmpp-server');
var AES = require("crypto-js/aes");
var CryptoJS = require("crypto-js");
/**
* #description all process variables
*/
require("./config/vars")(app);
var hostName = global.hzConfig.qualifiedHostName;
var config = require("./config/config.js")(app, express);
var friendsArr = [];
var server = null
var startServer = function(done) {
// Sets up the server.
console.log("start server.....");
console.log('xmpp server is listening on port ' + global.hzConfig.xmppServerPort + " on " + process.pid + ' !');
server = new xmppServer.C2S.BOSHServer({
port: global.hzConfig.xmppServerPort,
domain: 'localhost'
})
console.log("server");
console.log(server);
// On connection event. When a client connects.
server.on('connection', function(client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
console.log('connection');
client.on('register', function(opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function(opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === '') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
} else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function() {
console.log("client");
console.log(client.jid);
console.log('server:', client.jid, 'ONLINE');
friendsArr.push(client.jid);
console.log("friendsArr================>>>>>>>>>>>>>");
console.log(friendsArr);
//client.send(new xmppClient.Message({ type: 'chat' }).c('body').t("Hello there, little client."));
})
// Stanza handling
client.on('stanza', function(stanza) {
console.log(stanza);
console.log('server:', client.jid, 'stanza', stanza.toString())
var body = stanza.getChild('body');
var message = body.getText();
console.log("body===========>>>>>");
console.log(body);
console.log("message===========>>>>>");
console.log(message);
var from = stanza.attrs.from;
stanza.attrs.from = stanza.attrs.to;
stanza.attrs.to = friendsArr[0];
console.log("stanza.attrs");
var sendTo = "laxman#mailinator.com/";
friendsArr.map(function(obj) {
if (obj["user"] === "laxman") {
console.log(obj["_resource"]);
sendTo = sendTo + obj["_resource"];
}
});
//client.send(stanza)
// client.send(stanza)
//console.log("stanza.attrs.from");
//console.log(stanza.attrs.from);
console.log("sendTo++++++++++ ::::: " + sendTo);
var stanza = new xmppClient.Element('message', { to: sendTo, type: 'chat', 'xml:lang': 'ko' }).c('body').t('aaaaaMessage from admin1');
client.send(stanza);
console.log(stanza);
//client.send(new xmppClient.Message({to : sendTo, type: 'chat' }).c('body').t("Hello there, little client."));
})
// On Disconnect event. When a client disconnects
client.on('disconnect', function() {
console.log('server:', client.jid, 'DISCONNECT')
})
})
server.on('listening', function() {})
}
startServer();
message_service.js (clien side file)
(function() {
'use strict';
angular
.module("myApp")
.factory("HzXMPPService", ['$rootScope', '$cookies', '$location', 'HzServices',
function($rootScope, $cookies, $location, HzServices) {
console.log("*****************************************");
return {
OnConnectionStatus: function(conn, obj) {
console.log("conn");
console.log(conn);
console.log("Strophe.Status");
console.log(Strophe.Status);
this.OnConnected(conn);
},
OnConnected: function(conn) {
console.log("OnConnected call");
//Callback fired when availability status of your's or your friends changes.
conn.addHandler(this.OnPresenceStanza, null, "presence");
//callback fired while receiving message
conn.addHandler(this.OnMessageStanza, null, "message");
//callback fired when a friend/authorize request is received
conn.addHandler(this.OnSubscribeStanza, null, "presence", "subscribe");
//callback when your friend/authorize request is responded by another user.
conn.addHandler(this.OnSubscribedStanza, null, "presence", "subscribed");
//send presence to all who have added you to their contact list i.e., send online status to other clients. We are sending "available" status
//conn.send($pres());
},
OnPresenceStanza: function(stanza) {
console.log("OnPresenceStanza call");
var sFrom = $(stanza).attr('from');
console.log("sFrom");
console.log(sFrom);
var sBareJid = Strophe.getBareJidFromJid(sFrom);
console.log("sBareJid");
console.log(sBareJid);
var sTo = $(stanza).attr('to');
console.log("sTo");
console.log(sTo);
var sType = $(stanza).attr('type');
console.log("sType");
console.log(sType);
var sShow = $(stanza).find('show').text();
console.log("sShow");
console.log(sShow);
//OnSubscribeStanza();
//OnSubscribeStanza();
//sendAuthorizeRequest();
sendMessage();
return true;
},
//callback is also fired when other user is typing or paused.
OnMessageStanza: function(stanza) {
console.log("OnMessageStanza call");
console.log(stanza);
var STo = $(stanza).attr('to');
console.log("to");
console.log(STo);
var sType = $(stanza).attr('type');
console.log("sType");
console.log(sType);
var sBareJid = Strophe.getBareJidFromJid(STo);
console.log("sBareJid");
console.log(sBareJid);
var sBody = $(stanza).find('body').text();
console.log("sBody");
console.log(sBody);
if (sBody) {
console.log("A Message Received: " + sBody + " From " + STo);
}
return true;
},
OnSubscribeStanza: function(stanza) {
console.log("OnSubscribeStanza call");
if (stanza.getAttribute("type") == "subscribe") {
var from_id = stanza.getAttribute("from");
console.log("from_id");
console.log(from_id);
//send back authorize request to accept it.
conn.send($pres({ to: from_id, type: "subscribed" }));
}
return true;
},
OnSubscribedStanza: function(stanza) {
console.log("OnSubscribedStanza call");
if (stanza.getAttribute("type") == "subscribed") {
var from_id = stanza.getAttribute("from");
//send back confirm authorize request.
conn.send($pres({ to: from_id, type: "subscribed" }));
}
return true;
},
//make a friend request
sendAuthorizeRequest: function() {
conn.send($pres({ to: "rahul#mailinator.com", type: "subscribe" }));
},
//disconnect from XMPP server
disconnect: function() {
console.log("connected disconnect");
conn.flush();
conn.sync = true;
conn.disconnect();
},
//send a message.
sendMessage: function(conn, msg) {
console.log("Friends call .....");
console.log("conn.jid");
console.log(conn.jid);
//return false;
var message = $msg({ to: "laxman#mailinator.com", from: conn.jid, type: "chat" }).c("body").t(msg);
conn.send(message.tree());
},
onMessage: function(message) {
console.log('service message = ');
console.log(message);
return true;
},
createAccount: function() {
conn = new Strophe.Connection("localhost");
conn.register.connect("localhost", OnConnectionStatus, 60, 1);
}
}
}
]);
}());
For testing, I have used static user for sending a message to Laxman in the server side file.
My main issue is that message can not broadcast to my friends.

Facebook messenger that sends a message manually if the user subscribed

I'm making a bot that let my students get a school meal menu. I'd like it to send a list of menu to students 10 minutes before the lunch time.
How should I make a code for this in JavaScript?
The main problem I encountered with was how to check the time so that my bot can send a message at that time.
I also wonder if its code always runs on the Facebook server, so I can use while loop that always check a time.
I'd appreciate an advice. (I use MongoDB and node)
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var hey = ["Yeah! 😃"]
var reply;
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
app.get("/", function (req, res) {
res.send("Deployed!");
});
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
app.post('/webhook', function (req, res) {
var data = req.body;
if (data.object === 'page') {
if(d.getHours() === 10 && d.getMinutes() === 5)
sendTextMessage(senderID, "Success!");
data.entry.forEach(function(entry) {
var pageID = entry.id;
var timeOfEvent = entry.time;
entry.messaging.forEach(function(event) {
if (event.message) {
receivedMessage(event);
} else if(event.postback){
receivedPostback(event);
}
else {
console.log("Webhook received unknown event: ", event);
}
});
});
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
psid = senderID;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
switch (messageText) {
case 'Check':
sendTextMessage(senderID, "isSub: " + isSub);
sendTextMessage(senderID, "gamerNumber: " + gamerNumber);
sendTextMessage(senderID, "psid: " + senderID);
break;
----(and more)
function sendGenericMessage(recipientId, payload) {
var titlee
var subs
var image
switch(payload){
case "pmorning":
titlee = "Breakfast"
subs = //***this is the part where the db value goes in.***
image = "https://cdn.arstechnica.net/wp-content/uploads/sites/3/2016/10/Oculus-Rift-vs-HTC-Vive-vs-PlayStation-VR-1.jpg"
break;
---and more
}]
}]
}
}
}
};
sendTypingOn(recipientId);
callSendAPI(messageData);
}
Take a look at node-cron, which enables you to schedule jobs for running at specific times, specified by a CRON expression

implementing socket.io on existing application

My current application poll using MEAN stack and in controller I have a function vote() and API route defined as follow:
"/api/polls/pollID/pollChoiceID"
(ex. http://localhost:3001/api/polls/5587ad060a9e110816f9f1a8/5587ad060a9e110816f9f1a9)
I have the app working fine as it's but now I'm looking to implement socket.io on this app so that when client #2 connected and vote the voting result graph of client #1 will update in real time. I did some research about socket.io but I'm still stuck on implementing it.
For instance, in controller.js and inside the vote() I need to add:
socket.emit('send:vote', poll);
and over the routes/index.js I'll need to handle the socket.emit from controller so I wrap existing router.post codes with socket.on :
socket.on('send:vote', function(data){
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
//existing code here
}
}
However, Ii'm not sure if I'm taking the right steps so that they will work with my existing API route. Any inputs would be great! Thanks
/*
controller.js
*/
var voteObj = { poll_id1: pollSelected, choice1: pollChoiceSelected };
$scope.votedPollID = voteObj.poll_id1;
$scope.votedPollChoiceID = voteObj.choice1;
$scope.vote = function()
{
$http.post('/api/polls/' + $scope.votedPollID + '/' + $scope.votedPollChoiceID)
.success(function (data)
{
console.log(data);
$scope.poll = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
/*
routes/index.js
*/
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
var testpollid = req.params.poll_id2;
var testpollchoiceid = req.params.poll_choice2;
var ipCounter = 0;
PollModel.findById({_id: req.params.poll_id2}, function(err, poll)
{
if(poll)
{
var choice = poll.choices.id(testpollchoiceid);
choice.votes.push({ ip: ip });
var ipCounter = ipCounter++;
poll.save(function(err, doc)
{
if(err)
{
return (err);
}
else
{
var theDoc = {
question: doc.question, id: doc._id, choices: doc.choices,
userVoted: false, totalVotes: 0
};
for(var i = 0, ln = doc.choices.length; i< ln; i++)
{
var choice = doc.choices[i];
for(var j= 0, jLn = choice.votes.length; j< jLn; j++)
{
var vote = choice.votes[j];
theDoc.totalVotes++;
theDoc.ip = ip;
if(vote.ip === ip)
{
theDoc.userVoted = true;
theDoc.userChoice = { _id: choice._id, text: choice.text };
}
}
}
poll.userVoted = theDoc.userVoted;
}
});
return res.json(poll);
}
else
{
return res.json({error:true});
}
});
});
});
});

Resources