Skip to content

Instantly share code, notes, and snippets.

@hypernova7
Created February 16, 2024 07:56
Show Gist options
  • Save hypernova7/c8966712aeaf3c584958da3367e82125 to your computer and use it in GitHub Desktop.
Save hypernova7/c8966712aeaf3c584958da3367e82125 to your computer and use it in GitHub Desktop.
pittow
const sessions = new Map();
const chatHandler = async (ctx) => {
try {
await ctx.answerCallbackQuery();
} catch {}
const channels = process.env.TG_CHANNEL.split(',');
let notJoinedChannels = [];
for (let channel of channels) {
const member = await ctx.api.getChatMember(`@${channel.trim()}`, ctx.from.id).catch(err => err.status = 'left');
if (member.status === 'left' || member.status === 'kicked') {
notJoinedChannels.push(channel.trim());
}
}
if (notJoinedChannels.length !== 0) {
return await ctx.reply(`<b>⚠ You must join these channels to use the bot!\n - @${notJoinedChannels.join('\n - @')} </b>`, {
parse_mode: "HTML",
reply_markup: new InlineKeyboard()
.text('πŸ’¬ Chat now', 'chat')
});
}
// First time match
if (sessions.has(ctx.from.id)) sessions.set(`${ctx.from.id}`, {
matched: false,
matched_over: false,
initial_match: true
});
const session = sessions.get(`${ctx.from.id}`)
const user = await db.getData(ctx.from.id);
if (user.currentChatPartnerID !== 0) return await ctx.reply("<b>❗ You are already in a chat!</b>\n\n<i>Use /stop command to stop the chat.</i>", { parse_mode: "HTML" });
let availableList = await db.getWaitingList();
if (availableList.find(x => x.userRawInfo.telegramId == ctx.from.id)) return await ctx.reply('<b><i>⏳ You are already in the waiting list, you will be notified when someone is available</i></b>', { parse_mode: "HTML" });
const { message_id } = await ctx.reply('<b><i>πŸ”Ž Searching for a chat partner...</i></b>', { parse_mode: "HTML" });
// This line exists twice
// Ignore
// if (availableList.length == 0) {
// await db.addToWaitingList(ctx.from.id, user);
// await ctx.api.editMessageText(ctx.from.id, message_id, '<b><i>⏳ You are now in the waiting list, you will be notified when someone is available</i></b>', { parse_mode: "HTML" });
// return;
// }
availableList = availableList.filter(x => {
if (x.userRawInfo.telegramId == ctx.from.id) return false;
if (x.userRawInfo.telegramId == user.previousChatPartnerID) return false;
if (user.intrestGender != 'other') {
if (x.userRawInfo.myGender != user.intrestGender) return false;
}
if (x.userRawInfo.intrestGender != 'other') {
if (user.myGender != x.userRawInfo.intrestGender) return false;
}
if (user.tags.length > 0)
if (!x.userRawInfo.tags.some(r => user.tags.indexOf(r) >= 0)) return false;
if (x.userRawInfo.tags.length > 0)
if (!user.tags.some(r => x.userRawInfo.tags.indexOf(r) >= 0)) return false;
if (x.userRawInfo.currentChatPartnerID !== 0) return false;
if (user.intrestAge.min !== 0) {
if (user.intrestAge.min > x.userRawInfo.age) return false
}
if (user.intrestAge.max !== 0) {
if (user.intrestAge.max < x.userRawInfo.age) return false
}
if (x.userRawInfo.intrestAge.min !== 0) {
if (x.userRawInfo.intrestAge.min > user.age) return false
}
if (x.userRawInfo.intrestAge.max !== 0) {
if (x.userRawInfo.intrestAge.max < user.age) return false
}
return true;
});
// This is a possible fixure
if (!session.matched && session.initial_match && availableList.length == 0) {
await db.addToWaitingList(ctx.from.id, user);
await ctx.api.editMessageText(ctx.from.id, message_id, '<b><i>⏳ You are now in the waiting list, you will be notified when someone is available</i></b>', { parse_mode: "HTML" });
return;
}
let partner;
if (user.location.latitude == 0 || user.location.longitude == 0) {
partner = availableList[Math.floor(Math.random() * availableList.length)];
} else {
// Second possible fixure
if (!session.matched && session.initial_match && availableList.every(x => x.userRawInfo.location.latitude == 0 || x.userRawInfo.location.longitude == 0)) {
await db.addToWaitingList(ctx.from.id, user);
await ctx.api.editMessageText(ctx.from.id, message_id, '<b><i>⏳ You are now in the waiting list, you will be notified when someone is available</i></b>', { parse_mode: "HTML" });
return;
}
partner = findClosestUser(user.location.latitude, user.location.longitude, availableList);
}
let distance = "Unknown";
const userData = await db.getData(ctx.from.id);
const partnerData = await db.getData(partner.userRawInfo.telegramId);
// Third possible fixure
if (!session.matched && session.initial_match) {
await db.deleteFromWaitingList(partner._id);
await db.newChat(ctx.from.id, partnerData.telegramId);
await db.newChat(partnerData.telegramId, ctx.from.id);
await ctx.api.deleteMessage(ctx.from.id, message_id);
session.initial_match = false;
session.matched = true;
}
const validLocation = (data) => data.location.longitude !== 0 || data.location.latitude !== 0;
if (validLocation(userData) && validLocation(partnerData))
distance = getDistanceFromLatLonInKm(userData.location.latitude, userData.location.longitude, partnerData.location.latitude, partnerData.location.longitude);
await ctx.reply(`<b>βœ… Found a chat partner!</b>\n\n<b><i>πŸ‘€ Gender: ${partner.userRawInfo.myGender}\nπŸŽ‚ Age: ${partner.userRawInfo.age === 0 ? 'Unknown' : partner.userRawInfo.age}\nπŸ’Ÿ Tags: ${partner.userRawInfo.tags.length > 0 ? partner.userRawInfo.tags.join(', ') : 'No tags'}\n⛳️ Distance: ${distance !== "Unknown" ? `${distance.toFixed(2)} KM` : "Unknown"}</i></b>`, {
parse_mode: "HTML",
reply_markup: new Keyboard()
.text('🚫 Report')
.text('πŸ›‘ Stop').row()
.text('πŸ”™ Back')
.resized()
});
await ctx.api.sendMessage(partner.userRawInfo.telegramId, `<b>βœ… Found a chat partner!</b>\n\n<b><i>πŸ‘€ Gender: ${user.myGender}\nπŸŽ‚ Age: ${user.age === 0 ? 'Unknown' : user.age}\nπŸ’Ÿ Tags: ${user.tags.length > 0 ? user.tags.join(', ') : 'No tags'}\n⛳️ Distance: ${distance !== "Unknown" ? `${distance.toFixed(2)} KM` : "Unknown"}</i></b>`, {
parse_mode: "HTML",
reply_markup: new Keyboard()
.text('🚫 Report')
.text('πŸ›‘ Stop').row()
.text('πŸ”™ Back')
.resized()
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment