telegram webhook not working with database data - bots

i created a telegram bot. But instead of hard coding the replies, i decide to pull them from database.. below.. the problem is the bot does not return the data i pull from data base. it returns null in telegram.. but if i echo the variable
$mes['message']
in my browser it returns the valid data. what might be the problem?
$message1 = $db->prepare("SELECT message FROM about where id=1 ");
$message1->execute();
$mes = $message1->fetch();
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if ((strpos($text, "/start") === 0) || (strpos($text, "/start") === 0) ) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if (strpos($text, "/stop") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Did i do anything wrong?', 'reply_markup' => array(
'keyboard' => array(array('Yes', 'No')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
}else if ($text === "No") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
}else if ($text === "Tell me more") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => '<?php echo $mes2["message"];?>'));
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => '<?php echo $mes1["message"]; ?>'));
}
} else {
apiRequestJson("sendMessage", ['chat_id' => $chat_id, "text" => $me2 , 'reply_markup' => [
'keyboard' => [['Tell me more', 'Got it']],
'one_time_keyboard' => true,
'resize_keyboard' => true]]);
}

You don't need use <php echo for params in functions.
Look at you other variables like $chat_id, $me2... You should use "text" => $mes1["message"] and "text" => $mes2["message"]
it's already proccessed by PHP. You don't need to embed it one more time
}else if ($text === "Tell me more") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => $mes2["message"]));
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => $mes1["message"]));
}

i found out the problem.
the database object $text was not available in the function holding the if statements.
i had to declare it as global in the function.
e.g
function sendMessage () {
global $text;
//if statements here
}
it works fine now

Related

How to check multiconditions to concatenate an observable with rxjs

I would like to make check condition on message which is an observable and to costumize the output like this scenerio :
check if the messsage is to me or from me and concatenate 20 first caracters with the name of friend or if it is my message with you
chech the type of message if it is a photo or file to make a message you sent an attament for example
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
let message: Observable<string>;
const messageModel = this.allDirectMessages$
.pipe(
map((x) =>
x.filter(
(f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
)
)
)
.pipe(map((data) => data[data.length - 1].messageModel))
.pipe(
map((item) => {
if (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
else (item.to.userName == onlineUserModel.userName) {
message = concat("You", item.content, "...");
}
})
);
return message;
}
If you want to return the message as an Observable<string> you can do something like this:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}
I try to share you my result, just I added the map operator before filter:
getLastMessage(onlineUserModel: OnlineUserModel): Observable<string> {
return this.allDirectMessages$
.pipe(
filter((f) =>
f.messageModel.to.userName === onlineUserModel.userName ||
f.messageModel.from.userName === onlineUserModel.userName
),
map((data) => {
const item = data[data.length - 1].messageModel;
if (item.to.userName == onlineUserModel.userName) {
return `You ${item.content}...`;
}
else (item.from.userName == onlineUserModel.userName) {
return `Them ${item.content}...`;
}
})
);
}

Problem with maximun reactions Discord.js

my goal is to use a command that add reactions and you can react to change the text, so when I click and the reaction 1 that's edit the original text to : 1 and same for the others... that's pretty much working, but when i'm trying to remove and re-add the reaction, that's not working I think it's because of : { max: 1 } here's my code :
bot.on('message', msg => {
if(msg.content === PREFIX + "test") {
msg.channel.send(`${msg.author.username}, exemple`).then((sentMessage) => {
setTimeout(function() {
sentMessage.react("⏪");
}, 500);
setTimeout(function() {
sentMessage.react("⬅️");
}, 1000);
setTimeout(function() {
sentMessage.react("➡️");
}, 1500);
setTimeout(function() {
sentMessage.react("⏩");
}, 2000);
let reactionFilter = (reaction, user) => {
reaction.emoji.name === '⏪' && user.id !== "bot id" && user.id == msg.author.id
}
sentMessage.awaitReactions(reactionFilter, { max: 1 }).then(() => {
sentMessage.edit(`1`)
}
)
let reactionFilter2 = (reaction, user) => {
reaction.emoji.name === '⬅️' && user.id !== "bot id" && user.id === msg.author.id
}
sentMessage.awaitReactions(reactionFilter2, { max: 1 }).then(() => {
sentMessage.edit(`2`)
}
)
let reactionFilter3 = (reaction, user) => {
reaction.emoji.name === '➡️' && user.id !== "bot id" && user.id === msg.author.id
}
sentMessage.awaitReactions(reactionFilter3, { max: 1 }).then(() => {
sentMessage.edit(`3`)
}
)
let reactionFilter4 = (reaction, user) => {
reaction.emoji.name === '⏩' && user.id !== "bot id" && user.id === msg.author.id
}
sentMessage.awaitReactions(reactionFilter4, { max: 1 }).then(() => {
sentMessage.edit(`4`)
}
)
})
}
})
Thanks !
Yes it's because of the max limit, you should prob instead be using one reaction collector instead:
const emojis = ["⏪", "⬅️", "➡️", "⏩"];
//no need to check if the user id isnt the bot
const filter = (reaction, user) => emojis.includes(reaction.emoji.name) && user.id === msg.author.id;
// adding a time is probably a better option
const collector = sentMessage.createReactionCollector(filter, { time: 5000 });
collector.on("collect", reaction => {
// array is 0 indexed so just add 1 to the index and you get the number you wanted
// might need to convert the number into a string aswell
sentMessage.edit("" + (emojis.indexOf(reaction.emoji.name) + 1));
});
Should note this doesn't do anything if a reaction is removed, which I think is best because it would be hard to decide what the text should be after it's removed

I need to remove user reaction after reacting

I have a command which allows me to go and query an API to retrieve images and then display them in discord.
Currently I come to search from my API 10 images, I want to set up a navigation system thanks to the discord reactions. Everything works but the problem is that once the user has clicked the reaction remains active. I need to delete the reaction to improve the user experience. Currently it is therefore necessary to double click which is not very practical. Here's the method that doesn't work for deletion :
const removeReaction = (m, msg, emoji) => {
try {
m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id);
} catch(err) {
console.log('err: ', err)
}
}
here is all my code
bot.on('message', async msg => {
if (msg.content.startsWith('!test')) {
const args = msg.content.slice('!test').split(' ')
console.log('args :', args[1])
axios(`https://json-api.example.com/posts?tags=${args[1]}&limit=10`, {
method: 'GET',
})
.then((response) => {
if (response.status === 500) {
msg.channel.send('error')
} else {
if (response.data.posts.length === 0) {
msg.channel.send(`No result for ${args[1]}`)
}
if (response.data.posts.length > 0) {
const resultsLength = response.data.posts.length
const options = {
limit: 60000,
min: 1,
max: resultsLength - 1,
page: 1
}
const pages = []
response.data.posts.map((i, index) => {
pages.push({
"title": `Result page number ${index} for ${args[1]}`,
"url": `${response.data.posts[index].sample_url}`,
"color": 43333,
"footer": {
"icon_url": "https://cdn.discordapp.com/app-icons/708760465999790244/228b2993e942a361518b557ee4511b26.png?size=32",
"text": "Cool footer"
},
"image": {
"url": `${response.data.posts[index].url}`
},
"fields": [
{
"name": "tags",
"value": `${response.data.posts[index].tags[0] || '/'}, ${response.data.posts[index].tags[1] || '/'}, ${response.data.posts[index].tags[2] || '/'}, ${response.data.posts[index].tags[3] || '/'}`
}
]
})
})
const m = msg.channel.send({ embed: pages[options.page] }).then((el) => {
el.react('⬅️')
el.react('➡️')
el.react('🗑️')
})
const filter = (reaction, user) => {
return ['⬅️', '➡️', '🗑️'].includes(reaction.emoji.name) && user.id == msg.author.id
}
const awaitReactions = (msg, m, options, filter) => {
const { min, max, page, limit } = options
m.awaitReactions(filter, { max: 1, time: limit, errors: ['time'] })
.then((collected) => {
const reaction = collected.first()
const removeReaction = (m, msg, emoji) => {
try { m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id); } catch(err) { console.log('err: ', err) }
}
if (reaction.emoji.name === '⬅️') {
removeReaction(m, msg, '⬅️')
if (page != min) {
page = page - 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter)
}
else if (reaction.emoji.name === '➡️') {
removeReaction(m, msg, '➡️');
if (page != max) {
page = page + 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter);
}
else if (reaction.emoji.name === '➡️') {
removeReaction(m, msg, '➡️');
if (page != max) {
page = page + 1
m.edit({ embed: pages[page] })
}
awaitReactions(msg, m, options, filter);
}
else if (reaction.emoji.name === '🗑️') {
return m.delete()
}
else {
awaitReactions(msg, m, options, filter)
}
}).catch((err) => { console.log('err: ', err) })
}
awaitReactions(msg, m, options, filter)
Thanks in advance for your help
so, after much research I finally found. I share the answer here.
With the 12+ version of discord.js package a lot has evolved including my problem:
m.reactions.find(r => r.emoji.name == emoji).users.remove(msg.author.id);
must become :
m.reactions.cache.find(r => r.emoji.name == emoji).users.remove(msg.author);
I have made this code a while ago.
It is for an older version of Discord.js but according to docs it should still work.
Basically what you want to do is to use Discord.js createReactionCollector function after you send the picture, then inside this.reactionCollector.on('collect', (reaction, reactionCollector) => {//do your work here}) you can change the picture then call reaction.remove(user); which immediately removes the reaction for that user.
Here's my code:
Note: I have made a class for this command so it might look a bit different for you.
Also in my version, only the user who initially called the command can change the picture. So you will need to modify that part if you want to let anyone change the picture. (It might be a pretty bad idea if your bot is in a large server.)
this.channel.send({embed}).then(msg => {
this.message = msg;
this.message.react('⬅️').then(x => {
this.message.react('➡️');
})
const filter = (reaction, user) => {
return (reaction.emoji.name === '➡️' || reaction.emoji.name === '⬅️') && user.id === this.user.id;
};
this.reactionCollector = this.message.createReactionCollector(filter, { time: 600000 });
this.reactionCollector.on('collect', (reaction, reactionCollector) => {
if(reaction.emoji.name === '➡️') {
if(this.index + 1 < result.length) {
this.index++;
var embed = this.makeEmbed(result[this.index].img);
this.message.edit({embed});
}
}
else if(reaction.emoji.name === '⬅️') {
if(this.index - 1 > -1) {
this.index--;
var embed = this.makeEmbed(result[this.index].img);
this.message.edit({embed});
}
}
reaction.remove(this.user);
});
});

Laravel excel, iterate item to insert data

My excel file consists of student id, name, and course which i'm saving in database. The data was separated by gender in which at row[0]. what i'm trying to achieve here is how can i iterate my data and insert a gender in my database.?
Sample sample.xlsx
//StudentController
Excel::import(new StudentsImport, request()->file('import'));
//ImportSheet
public function model(array $row)
{
//empty rows
if (!isset($row[1]) || $row[0] == '#') {
return null;
}
if (isset($row[1])) {
return new Student([
'id_number' => $row[1],
'name' => $row[2],
'course' => $row[3],
'gender' => 'male || female', //<--- HOW CAN I INSERT GENDER HERE BASE ON THE JPEG ABOVE?
]);
}
}
Here is the way this may help you to get your gender:
public function model(array $row)
{
//empty rows
if (!isset($row[1]) || $row[0] == '#') {
return null;
}
//get the gender
$gender = ''; // default is empty, you can also assign some default value
if (isset($row[0]) && (strtolower($row[0]) == 'male' || strtolower($row[0]) == 'female')) {
$gender = $row[0];
}
if (isset($row[1])) {
return new Student([
'id_number' => $row[1],
'name' => $row[2],
'course' => $row[3],
'gender' => $gender
]);
}
}

Discord.j - Function strangely empty

this question is linked to another one. If you need to know why I'm asking this, check this question.
I'm developing a bot who should get a collection filled with members who have a specific role. But after testing and double checking role name and be sure I'm testing the bot in a server and not in DM the collection is always empty and unusable (the program couldn't run without it).
const eventMembers = message.guild.members.cache.filter(m =>
m.roles.cache.some(r => r.name === "event")
);
const connectedMembers = eventMembers.members.filter(m => {
return voiceChannel.members.has(m.id)
});
console.log(connectedMembers);
If anybody has a hint or a solution I take it
You forgot return :)
const eventMembers = message.guild.members.cache.filter(m => {
return m.roles.cache.some(r => r.name === "event")
});
or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event"));
You can check for the role with this name exist:
let role = message.guild.roles.cache.find(role => role.name === 'event')
if (role) {
console.log('ok')
} else {
console.log('No role found with this nickname')
}
V2
const eventMembers = message.guild.members.cache.filter(m => {
return m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID
});
or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID)
V3 :D
bot.on('message', message => {
if(message.content === '!test') {
if(!message.member.voice.channel) return message.reply('You need joinVoiceChannel for use this command');
let targetRole = message.guild.roles.cache.find(role => role.name === 'event')
if (!targetRole) return message.reply('Can`t find a role');
let eventMembersNotInVoice = targetRole.members.filter(member => member.voice.channelID !== message.member.voice.channelID)
console.log(eventMembersNotInVoice.size)
}
});

Resources