Skip to content

Commit

Permalink
matching works again
Browse files Browse the repository at this point in the history
  • Loading branch information
johan-t committed Oct 23, 2023
1 parent 335beac commit e017b87
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 62 deletions.
2 changes: 1 addition & 1 deletion commands/match-command.ts
@@ -1,6 +1,6 @@
import { db } from '../common';
import 'dotenv/config';
import questions from '../questions.json';
import { questions } from '../questions';
import { sendQuestion } from './test-command';
import { ChatInputCommandInteraction } from "discord.js";

Expand Down
17 changes: 12 additions & 5 deletions commands/test-command.ts
@@ -1,7 +1,7 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, SlashCommandBuilder, Guild, Role, User, TextChannel, ChatInputCommandInteraction } from 'discord.js';
import cron from 'cron';
import 'dotenv/config';
import questions from '../questions.json';
import { questions } from '../questions';
import { db, client } from "../common";
import { encrypt, decrypt } from "../encryptionUtils";
import { findMatchingUser } from "../functions/findMatchingUser";
Expand Down Expand Up @@ -202,7 +202,7 @@ async function initiateConversation(interaction: any, userResponses: number[]):
if (bestMatchId) {
const isMember = await guild.members.fetch(bestMatchId).then(() => true).catch(() => false);
if (!isMember) {
await db.db('contrabot').collection("users").deleteOne({ bestMatchId });
await db.db('contrabot').collection("users").deleteOne({ userId: bestMatchId }); // Modified the key to userId for deletion
console.log(`Deleted: userId ${bestMatchId} is no longer on the server.`);
return await initiateConversation(interaction, userResponses);
}
Expand All @@ -217,6 +217,13 @@ async function initiateConversation(interaction: any, userResponses: number[]):
const bestMatch = await guild.members.fetch(bestMatchId);
if (!bestMatch) throw new Error('bestMatch.GuildMember was not found');

// Fetch and decrypt bestMatch's userVector
const bestMatchData = await db.db('contrabot').collection("users").findOne({ userId: bestMatchId });
if (!bestMatchData || !bestMatchData.userVector) {
throw new Error(`UserVector for userId ${bestMatchId} was not found in the database`);
}
const bestMatchUserVector = JSON.parse(decrypt(bestMatchData.userVector));

const matchesCategory = guild.channels.cache.find((category: any) => category.name === 'matches' && category.type === 4);
const channelName = `match-${interaction.user.username}-${bestMatch.user.username}`;

Expand All @@ -240,11 +247,11 @@ async function initiateConversation(interaction: any, userResponses: number[]):
ViewChannel: false,
});

await textChannel.send(`Hallo ${interactionGuildMember} 👋, hallo ${bestMatch.user.username} 👋, basierend auf unserem Algorithmus wurdet ihr als Gesprächspartner ausgewählt. Bitte vergesst nicht respektvoll zu bleiben. Viel Spaß bei eurem Match!`);
await textChannel.send(`Hallo <@${interactionGuildMember.user.id}> 👋, hallo <@${bestMatch.user.id}> 👋, basierend auf unserem Algorithmus wurdet ihr als Gesprächspartner ausgewählt. Bitte vergesst nicht respektvoll zu bleiben. Viel Spaß bei eurem Match!`);
await textChannel.send(`Bei beispielsweise diesen drei Fragen seid ihr nicht einer Meinung:`);

// This function will send starter questions where they disagreed
conversationStarter(textChannel, interaction, bestMatch, userResponses);
// Pass bestMatchUserVector to conversationStarter
conversationStarter(textChannel, interaction, bestMatchUserVector, userResponses, bestMatchId);

interaction.user.send(`Du wurdest erfolgreich mit **@${bestMatch.user.username}** gematcht. Schau auf den Discord-Server um mit dem Chatten zu beginnen! 😊`);
client.users.fetch(bestMatchId).then(user => {
Expand Down
28 changes: 16 additions & 12 deletions functions/conversationStarter.ts
@@ -1,24 +1,28 @@
import { EmbedBuilder, User } from 'discord.js';
import questions from '../questions.json';
import { questions } from '../questions';
import { CronJob } from "cron";
import { client, db } from "../common";

export async function conversationStarter(channelOfDestination: any, interaction: any, bestMatch: any, user: number[]) {
export async function conversationStarter(channelOfDestination: any, interaction: any, bestMatchUserVector: number[], userResponses: number[], bestMatchId: string) {
// get all contrasting and similar answers
let addedToDisagree = false; // Track if any numbers were added to disagree
const disagree: number[] = [];

user.forEach((value, i) => {
const total = value + bestMatch.userVector[ i ];
if (bestMatchUserVector == null) {
console.error("the BestMatch userVector is null")
}

userResponses.forEach((value, i) => {
const total = value + bestMatchUserVector[i];
if (value !== 0 && total === 0) {
disagree.push(i);
addedToDisagree = true;
}
});
// Only add to disagree if the flag is still false
if (!addedToDisagree || disagree.length < 6) {
user.forEach((value, i) => {
const total = value + bestMatch.userVector[ i ];
userResponses.forEach((value, i) => {
const total = value + bestMatchUserVector[i];
if (Math.abs(total) === 1) {
disagree.push(i);
}
Expand All @@ -33,7 +37,7 @@ export async function conversationStarter(channelOfDestination: any, interaction

client.on('messageCreate', (message: any) => {
if (message.channel.id === channelOfDestination.id) {
if (message.author.id === bestMatch.userId) {
if (message.author.id === bestMatchId) {
bestMatchSentMessage = true;
return;
}
Expand Down Expand Up @@ -76,22 +80,22 @@ export async function conversationStarter(channelOfDestination: any, interaction
if (!bestMatchSentMessage && conv.eightHourNotificationSent) {
//Send messages to both users
interaction.user.send(`Dein Gesprächspartner hat das Gespräch verlassen. Wir finden einen neuen Gesprächspartner für dich.`);
client.users.fetch(String(bestMatch.userId)).then((user: User) => {
client.users.fetch(String(bestMatchId)).then((user: User) => {
user.send(`Aufgrund von Inaktivität wurde das Gespräch beendet. Bitte starte einen neuen Test, um einen neuen Gesprächspartner zu finden.`);
});

// Delete the channel, conversation and BestMatch from the database
channelOfDestination.delete();
db.db('contrabot').collection("conversations").deleteOne({ _id: conv._id });
await db.db('contrabot').collection("users").deleteOne({ userId: bestMatch.userId });
await db.db('contrabot').collection("users").deleteOne({ userId: bestMatchId });
}
});
});
twentyFourHourCheck.start();
}

function getRandomDisagreement(arr: number[], num: number) {
return Array.from({ length: Math.min(num, arr.length) }, () => arr.splice(Math.floor(Math.random() * arr.length), 1)[ 0 ]);
return Array.from({ length: Math.min(num, arr.length) }, () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]);
}

function sendDisagreedQuestions(channelOfDestination: any, disagree: number[]) {
Expand All @@ -100,15 +104,15 @@ function sendDisagreedQuestions(channelOfDestination: any, disagree: number[]) {
embeds: [
new EmbedBuilder()
.setTitle(`Frage: ${value + 1}/38`)
.setDescription(questions[ value ].question)
.setDescription(questions[value].question)
.setColor('#fb2364')
]
});
});

// Make it so that the tags of the questions are printed properly
const selectedTags = disagree
.map(index => questions[ index ].tag)
.map(index => questions[index].tag)
.filter(tag => tag)
.slice(0, 3);

Expand Down
24 changes: 20 additions & 4 deletions functions/findMatchingUser.ts
@@ -1,12 +1,25 @@
import { db } from '../common';
import { decrypt } from "../encryptionUtils";

export async function findMatchingUser(userId: string, userResponses: number[]): Promise<string | null> {
export async function findMatchingUser(userId: string, userResponses: any[]): Promise<string | null> {
if (userResponses.length === 0) {
console.log("No User Responses");
return null;
}

// Fetch users the current user has interacted with
const conversations = await db.db('contrabot').collection("conversations").find({
$or: [
{ interactionUserId: userId },
{ bestMatchUserId: userId }
]
}).toArray();

// Create a set of userIds that the current user has interacted with
const interactedUserIds = new Set(conversations.map(conv => {
return conv.interactionUserId === userId ? conv.bestMatchUserId : conv.interactionUserId;
}));

const users = await db.db('contrabot').collection("users").find().toArray();

let mostOppositeUser: string | null = null;
Expand All @@ -15,6 +28,10 @@ export async function findMatchingUser(userId: string, userResponses: number[]):
for (const user of users) {
if (user.userId === userId)
continue;
if (interactedUserIds.has(user.userId)) {
console.log(`Skipped: userId ${user.userId} has already interacted with userId ${userId}`);
continue;
}

let decryptedUserVector: number[]; // Explicit type declaration
if (typeof user.userVector === 'string') { // Check if it's a string
Expand All @@ -29,14 +46,13 @@ export async function findMatchingUser(userId: string, userResponses: number[]):
continue;
}


if (!Array.isArray(decryptedUserVector) || decryptedUserVector.length === 0) {
console.log(`Skipped: Missing or invalid decrypted userVector for userId ${user.userId}`);
continue;
}

const differenceScore = userResponses.reduce((acc, value, index) => {
return acc + value * decryptedUserVector[ index ];
return acc + value * decryptedUserVector[index];
}, 0);

if (differenceScore < lowestDifferenceScore) {
Expand All @@ -46,4 +62,4 @@ export async function findMatchingUser(userId: string, userResponses: number[]):
}

return mostOppositeUser;
}
}
40 changes: 0 additions & 40 deletions questions.json

This file was deleted.

0 comments on commit e017b87

Please sign in to comment.