Skip to content

Commit

Permalink
Merge pull request #71 from Contraversum/activity-issue
Browse files Browse the repository at this point in the history
Activity issue
  • Loading branch information
TheLlamamarketer committed Oct 21, 2023
2 parents 92cc568 + 18bf06d commit 48879c0
Showing 1 changed file with 141 additions and 64 deletions.
205 changes: 141 additions & 64 deletions commands/test/test-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ const checkForFeedbackRequests = async () => {
if (discordUser) {
await discordUser.send({
content: `
Hallo 👋, vor einer Woche hast du den Test ausgefüllt.
Wir können Contraversum nur durch Feedback unserer Nutzerinnen und Nutzer verbessern.
Daher wäre es ein wichtiger Beitrag für das Projekt und damit auch für die Depolarisierung
der Gesellschaft, wenn du uns Feedback geben könntest. Es dauert weniger als 3 Minuten. Vielen Dank, dein ContraBot ❤️`,
Hallo 👋, vor einer Woche hast du den Test ausgefüllt.
Wir können Contraversum nur durch Feedback unserer Nutzerinnen und Nutzer verbessern.
Daher wäre es ein wichtiger Beitrag für das Projekt und damit auch für die Depolarisierung
der Gesellschaft, wenn du uns Feedback geben könntest. Es dauert weniger als 3 Minuten. Vielen Dank, dein ContraBot ❤️`,
components: [actionRow]
});

Expand Down Expand Up @@ -217,71 +217,22 @@ export const sendQuestion = async (interaction: any) => {
$set: {
userId: interaction.user.id,
username: interaction.user.username,

currentQuestionIndex: currentQuestionIndex + 1,
userVector: encryptedUserVector,
feedbackRequestSent: false,
currentQuestionIndex: currentQuestionIndex + 1,
userVector: encryptedUserVector,
currentFeedbackQuestionIndex: 0,
invited: interaction.user.invited,
joined: interaction.user.joinedTimestamp

},
$setOnInsert: {
feedbackRequestSent: false
}
},
{ upsert: true }
);
} else {
const guildId = process.env.GUILD_ID;
if (!guildId) throw new Error('GUILD_ID not found');

const guild: Guild | undefined = client.guilds.cache.get(guildId);
if (!guild) throw new Error('Guild not found');

const bestMatch = await findMatchingUser(interaction.user.id, userResponses, guild);
if (bestMatch) {
const interactionGuildMember = guild.members.cache.get(interaction.user.id);
if (!interactionGuildMember) throw new Error('interactionGuildMember was nog found');

bestMatch.GuildMember = await guild.members.fetch(bestMatch.userId);
if (!guild) throw new Error('bestMatch.GuildMember');

const matchesCategory = guild.channels.cache.find((category: any) => category.name === 'matches' && category.type === 4);

const channelName = `match-${interaction.user.username}-${bestMatch.username}`;

const textChannel = await guild.channels.create({
parent: matchesCategory?.id,
name: channelName.toLowerCase(),
type: 0,
});

await textChannel.permissionOverwrites.edit(interactionGuildMember, {
ViewChannel: true,
SendMessages: true,
});
await textChannel.permissionOverwrites.edit(bestMatch.GuildMember, {
ViewChannel: true,
SendMessages: true,
});

const everyone = await guild.roles.everyone;

await textChannel.permissionOverwrites.edit(everyone, {
ViewChannel: false,
});

await textChannel.send(`Hallo ${interactionGuildMember} 👋, hallo ${bestMatch.GuildMember} 👋, 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:`);
conversationStarter(textChannel, interaction, bestMatch.userVector, userResponses);

interaction.user.send(`Du wurdest erfolgreich mit **@${bestMatch.username}** gematcht. Schau auf den Discord-Server um mit dem Chatten zu beginnen! 😊`);

verifyUser(interaction, guild);
} else {
initiateConversation(interaction, userResponses);

}
else {
console.warn('No best match found');
interaction.user.send("Leider konnte zur Zeit kein geeigneter Gesprächspartner gefunden werden. Bitte versuchen Sie es später erneut.");
}
// Reset context for this user in the database
await db.db('contrabot').collection("users").updateOne(
{ userId: interaction.user.id },
Expand All @@ -295,14 +246,80 @@ export const sendQuestion = async (interaction: any) => {
}
}

async function conversationStarter(channelOfDestination: any, interaction: any, bestMatch: number[], user: number[]) {
async function initiateConversation(interaction: any, userResponses: number[]) {
const guildId = process.env.GUILD_ID;
if (!guildId) throw new Error('GUILD_ID not found');

const guild: Guild | undefined = client.guilds.cache.get(guildId);
if (!guild) throw new Error('Guild not found');

const bestMatch = await findMatchingUser(interaction.user.id, userResponses, guild);
if (!bestMatch) {
console.warn('No best match found');
interaction.user.send("Leider konnte zur Zeit kein geeigneter Gesprächspartner gefunden werden. Bitte versuchen Sie es später erneut.");
return;
}

const interactionGuildMember = guild.members.cache.get(interaction.user.id);
if (!interactionGuildMember) throw new Error('interactionGuildMember was not found');

bestMatch.GuildMember = await guild.members.fetch(bestMatch.userId);
if (!bestMatch.GuildMember) throw new Error('bestMatch.GuildMember was not found');

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

const textChannel = await guild.channels.create({
parent: matchesCategory?.id,
name: channelName.toLowerCase(),
type: 0,
});

await textChannel.permissionOverwrites.edit(interactionGuildMember, {
ViewChannel: true,
SendMessages: true,
});
await textChannel.permissionOverwrites.edit(bestMatch.GuildMember, {
ViewChannel: true,
SendMessages: true,
});

const everyone = await guild.roles.everyone;
await textChannel.permissionOverwrites.edit(everyone, {
ViewChannel: false,
});

await textChannel.send(`Hallo ${interactionGuildMember} 👋, hallo ${bestMatch.GuildMember} 👋, 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);

interaction.user.send(`Du wurdest erfolgreich mit **@${bestMatch.username}** gematcht. Schau auf den Discord-Server um mit dem Chatten zu beginnen! 😊`);
client.users.fetch(String(bestMatch.userId)).then((user: User) => {
user.send(`Du wurdest mit **@${interaction.user.username}** gematcht. Schau auf den Discord-Server um mit dem Chatten zu beginnen! 😊`);
});

verifyUser(interaction, guild);

// Add conversation to database
const conversationInitiationTime = new Date();
await db.db('contrabot').collection('conversations').insertOne({
initiationTime: conversationInitiationTime,
interactionUserId: interaction.user.id,
bestMatchUserId: bestMatch.userId,
channelId: textChannel.id,
eightHourNotificationSent: false
});
}

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

const selectedIndexes = getRandomDisagreement(disagree, 6);
sendDisagreedQuestions(channelOfDestination, selectedIndexes.slice(0, 3));


let bestMatchSentMessage = false;

client.on('messageCreate', (message: any) => {
if (message.channel.id === channelOfDestination.id) {
if (message.author.id === bestMatch.userId) {
bestMatchSentMessage = true;
return;
}
}
});

// send message into the channel after 8 hours if no message was sent
const eightHourCheck = new cron.CronJob('0 */8 * * *', async () => {
const conversations = await db.db('contrabot').collection('conversations').find({
channelId: channelOfDestination.id
}).toArray();

conversations.forEach(async (conv) => {
if (!bestMatchSentMessage && !conv.eightHourNotificationSent) {
await channelOfDestination.send({
embeds: [
new EmbedBuilder()
.setTitle(`👋 Hallo ${interaction.user.username}, dein Gesprächspartner hat sich noch nicht gemeldet.`)
.setDescription(`Nach 24 Stunden inactivität wirst du ein neuen Gesprächspartner erhalten.`)
.setColor('#fb2364')
]
});
// update flag in the database
await db.db('contrabot').collection('conversations').updateOne(
{ channelId: channelOfDestination.id },
{ $set: { eightHourNotificationSent: true } }
);
}
});

});
eightHourCheck.start();

const twentyFourHourCheck = new cron.CronJob('0 0 */1 * *', async () => {
const conversations = await db.db('contrabot').collection('conversations').find({
channelId: channelOfDestination.id
}).toArray();

conversations.forEach(async (conv) => {
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) => {
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 });
}
});
});
twentyFourHourCheck.start();
}

function getRandomDisagreement(arr: number[], num: number) {
Expand Down Expand Up @@ -349,7 +427,6 @@ function sendDisagreedQuestions(channelOfDestination: any, disagree: number[]) {
}

async function findMatchingUser(userId: string, userResponses: number[], guild: Guild): Promise<{ userId: string, username: string, userVector: number[], GuildMember: any } | null> {

if (!userId || !Array.isArray(userResponses) || userResponses.length === 0) {
console.log("Invalid input parameters");
return null;
Expand Down

0 comments on commit 48879c0

Please sign in to comment.