Skip to content

Commit

Permalink
WIP breaking changes
Browse files Browse the repository at this point in the history
  • Loading branch information
GregTCLTK committed Oct 22, 2023
1 parent da3729e commit d882553
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 108 deletions.
9 changes: 4 additions & 5 deletions commands/match/match-command.ts → commands/match-command.ts
@@ -1,11 +1,10 @@
import { SlashCommandBuilder, Guild } from 'discord.js';
import { db } from '../../common';
import { db } from '../common';
import 'dotenv/config';
import questions from '../../questions';
import { sendQuestion } from '../test/test-command';
import questions from '../questions';

Check failure on line 4 in commands/match-command.ts

View workflow job for this annotation

GitHub Actions / Build Bot (20.x)

Cannot find module '../questions' or its corresponding type declarations.
import { sendQuestion } from './test-command';

export const data = new SlashCommandBuilder().setName('match').setDescription('Requests new match without retaking the test.');
export const execute = async (interaction: any) => {
export async function executeMatch(interaction: any) {

const userContext = await db.db('contrabot').collection("users").findOne({ userId: interaction.user.id });

Expand Down
28 changes: 13 additions & 15 deletions commands/test/test-command.ts → commands/test-command.ts
@@ -1,10 +1,10 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, SlashCommandBuilder, Guild, Role, User, TextChannel } from 'discord.js';
import { client, db } from '../../common';
import { client, db } from '../common';
import cron from 'cron';
import 'dotenv/config';
import questions from '../../questions';
import findMatchingUser from '../../functions/findMatchingUser';
import conversationStarter from '../../functions/conversationStarter';
import questions from '../questions';

Check failure on line 5 in commands/test-command.ts

View workflow job for this annotation

GitHub Actions / Build Bot (20.x)

Cannot find module '../questions' or its corresponding type declarations.
import findMatchingUser from '../functions/findMatchingUser';
import conversationStarter from '../functions/conversationStarter';

const checkForFeedbackRequests = async () => {
const now = new Date();
Expand All @@ -31,11 +31,11 @@ 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.
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]
components: [ actionRow ]
});

// Update context for this user in the database
Expand Down Expand Up @@ -93,7 +93,7 @@ const sendTestReminder = async () => {
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

for (const [userID, member] of members) {
for (const [ userID, member ] of members) {
const joinDate = member.joinedAt;
if (!joinDate) continue;

Expand All @@ -108,7 +108,7 @@ const sendTestReminder = async () => {
await member.send("Hey 👋, du hast den Test noch nicht ausgefüllt. Wir würden uns freuen, wenn du den Test noch ausfüllst, damit du mit anderen Usern gematcht werden kannst.");
await member.send("Um einen Test zu starten, tippe /test in den Server ein oder klicke auf die rote Taste 'Test starten' im Channel #how-to-basics.");

// Add the user to the database and creates reminderSent status
// Add the user to the database and creates reminderSent status
await db.db('contrabot').collection('users').updateOne(
{ userId: userID },
{
Expand Down Expand Up @@ -143,7 +143,7 @@ export const sendQuestion = async (interaction: any) => {
if (currentQuestionIndex < questions.length) {
const embed = new EmbedBuilder()
.setTitle("Frage: " + currentQuestionDisplay + "/38")
.setDescription(questions[currentQuestionIndex].question)
.setDescription(questions[ currentQuestionIndex ].question)
.setColor('#fb2364');

const builder = new ActionRowBuilder<ButtonBuilder>().addComponents([
Expand All @@ -162,8 +162,8 @@ export const sendQuestion = async (interaction: any) => {
]);

interaction.user.send({
embeds: [embed],
components: [builder]
embeds: [ embed ],
components: [ builder ]
});


Expand Down Expand Up @@ -263,12 +263,10 @@ function verifyUser(interaction: any, guild: Guild) {
interactionGuildMember.roles.add(role).catch(console.error);
}

export const data = new SlashCommandBuilder().setName('test').setDescription('Asks the test questions!');
export const execute = async (interaction: any) => {
export async function executeTest(interaction: any) {
await interaction.reply({
content: 'Deine Meinung ist gefragt! Bitte kommentiere die folgenden These mit 👍, 👎 oder 😐. Test wurde gestartet.\nBitte schaue in deinen Direktnachrichten nach :)',
ephemeral: true,
});
sendQuestion(interaction);
};

90 changes: 46 additions & 44 deletions index.ts
@@ -1,52 +1,57 @@
import 'dotenv/config'
import { Events } from 'discord.js';
import { sendQuestion, sendTestButton } from './commands/test/test-command';
import { Events, REST, Routes } from 'discord.js';
import { executeTest, sendQuestion, sendTestButton } from './commands/test-command';
import { sendSurveyQuestions, Feedbackquestions } from './functions/startSurvey';
import * as fs from 'fs';
import path from 'path'
import { google } from 'googleapis';
import { client, db, ClientWithCommands } from './common';
import { client, db } from './common';
import { executeMatch } from "./commands/match-command";

client.on(Events.ClientReady, async (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
await db.connect();
});
client.login(process.env.TOKEN); // Log in to the bot

client.on("ready", () => {
client.on(Events.ClientReady, async c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
await db.connect();
sendTestButton()
});
//add later
//client.user.setActivity("123", {ActivityType.Listening})

// Load commands
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.ts'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
const rest = new REST().setToken(process.env.TOKEN!);

(async () => {
try {
console.log('Started refreshing application (/) commands.');

await rest.put(Routes.applicationCommands(client.user!.id), {
body:
[
{
name: 'match',
description: 'Requests new match without retaking the test.'
},
{
name: 'test',
description: 'Asks the test questions!'
},
]
});

console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
}
}
})();

});

// Catch command errors
client.on(Events.InteractionCreate, async (interaction) => {
client.on(Events.InteractionCreate, async interaction => {
// Handle Slash commands
if (interaction.isChatInputCommand()) {
const command = (interaction.client as ClientWithCommands).commands.get(interaction.commandName);

if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}

try {
await command.execute(interaction);
if (interaction.commandName === 'test')
await executeTest(interaction);
else if (interaction.commandName === 'match')
await executeMatch(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
Expand Down Expand Up @@ -123,7 +128,7 @@ const jwtClient = new google.auth.JWT(
process.env.CLIENT_EMAIL,
undefined,
process.env.PRIVATE_KEY,
['https://www.googleapis.com/auth/spreadsheets']
[ 'https://www.googleapis.com/auth/spreadsheets' ]
);

const sheets = google.sheets({ version: 'v4', auth: jwtClient });
Expand All @@ -139,15 +144,15 @@ client.on(Events.MessageCreate, async (message) => {
let currentFeedbackQuestionIndex = userContext?.currentFeedbackQuestionIndex || 0;

// Calculate the column where the answer should be placed.
const columnForAnswer = COLUMNS[currentFeedbackQuestionIndex + 1]; // +1 to skip the first column which might have the userID
const columnForAnswer = COLUMNS[ currentFeedbackQuestionIndex + 1 ]; // +1 to skip the first column which might have the userID

// Find the row number for the current user (assuming the user's ID is in the first column)
const response = await sheets.spreadsheets.values.get({
spreadsheetId: SHEET_ID,
range: `${START_COLUMN}:${START_COLUMN}` // search in the first column only
});
const rows = response.data.values || [];
let rowIndex = rows.findIndex((row: any) => row[0] === message.author.id.toString()) + 1; // +1 because index is 0-based and rows in Google Sheets are 1-based.
let rowIndex = rows.findIndex((row: any) => row[ 0 ] === message.author.id.toString()) + 1; // +1 because index is 0-based and rows in Google Sheets are 1-based.

// If the user is not found, create a new row for them
if (rowIndex === 0) {
Expand All @@ -158,7 +163,7 @@ client.on(Events.MessageCreate, async (message) => {
insertDataOption: 'INSERT_ROWS',
resource: {
values: [
[message.author.id] // userID in the first column
[ message.author.id ] // userID in the first column
]
}
} as any);
Expand All @@ -172,15 +177,15 @@ client.on(Events.MessageCreate, async (message) => {
valueInputOption: 'RAW',
resource: {
values: [
[message.content]
[ message.content ]
]
}
} as any);

currentFeedbackQuestionIndex++;

if (currentFeedbackQuestionIndex < Feedbackquestions.length) {
message.author.send(Feedbackquestions[currentFeedbackQuestionIndex]);
message.author.send(Feedbackquestions[ currentFeedbackQuestionIndex ]);

await db.db('contrabot').collection("users").updateOne(
{ userId: message.author.id },
Expand All @@ -206,6 +211,3 @@ client.on(Events.MessageCreate, async (message) => {
console.error("Error in Events.MessageCreate:", error);
}
});


export { client, db };
40 changes: 40 additions & 0 deletions questions.json
@@ -0,0 +1,40 @@
[
{ "question": "Auf allen Autobahnen soll ein generelles Tempolimit gelten.", "tag": ["Verkehrssicherheit", " Klimawandel"] },
{ "question": "Deutschland soll seine Verteidigungsausgaben erhöhen.", "tag": "Verteidigungspolitik" },
{ "question": "Bei Bundestagswahlen sollen auch Jugendliche ab 16 Jahren wählen dürfen.", "tag": ["Wahlalter", "Demokratie"] },
{ "question": "Die Förderung von Windenenergie soll beendet werden?", "tag": ["Energiepolitik", "Klimawandel"] },
{ "question": "Die Möglichkeiten der Vermieterinnen und Vermieter, Wohnungsmieten zu erhöhen, sollen gesetzlich stärker begrenzt werden.", "tag": ["Mietpreisbremse", "Wohnraumkosten"] },
{ "question": "Die Ukraine soll Mitglied der Europäischen Union werden dürfen.", "tag": ["EU-Erweiterung", "Ukraine Krieg"] },
{ "question": "Der geplante Ausstieg aus der Kohleverstromung soll vorgezogen werden.", "tag": ["Energiepolitik", "Umweltschutz"] },
{ "question": "Alle Erwerbstätigen sollen in der gesetzlichen Rentenversicherung versichert sein müssen.", "tag": "Sozialpolitik" },
{ "question": "Das Recht anerkannter Flüchtlinge auf Familiennachzug soll abgeschafft werden.", "tag": "Migrationspolitik" },
{ "question": "Auf den Umsatz, der in Deutschland mit digitalen Dienstleistungen erzielt wird, soll eine nationale Steuer erhoben werden.", "tag": "Steuerpolitik" },
{ "question": "Die traditionelle Familie aus Vater, Mutter und Kindern soll stärker als andere Lebensgemeinschaften gefördert werden.", "tag": "Familienpolitik" },
{ "question": "Spenden von Unternehmen an Parteien sollen weiterhin erlaubt sein.", "tag": "Parteienfinanzierung" },
{ "question": "Migration in die Europäische Union sollte erleichtert werden.", "tag": "Migrationspolitik" },
{ "question": "Studentinnen und Studenten sollen BAföG unabhängig vom Einkommen ihrer Eltern erhalten.", "tag": "Bildungspolitik" },
{ "question": "In Deutschland soll es generell möglich sein, neben der deutschen eine zweite Staatsbürgerschaft zu haben.", "tag": ["Staatsbürgerschaft", "Migrationspolitik"] },
{ "question": "Bundesbehörden sollen in ihren Veröffentlichungen unterschiedliche Geschlechtsidentitäten sprachlich berücksichtigen müssen.", "tag": ["Genderpolitik", "Minderheitenpolitik"] },
{ "question": "Der Solidaritätszuschlag soll vollständig abgeschafft werden.", "tag": ["Steuerpolitik", "Solidaritätszuschlag"] },
{ "question": "Das Tragen eines Kopftuchs soll Beamtinnen im Dienst generell erlaubt sein.", "tag": ["Religionsfreiheit", "Minderheitenpolitik"] },
{ "question": "Die Zulassung von neuen Autos mit Verbrennungsmotor soll auch langfristig möglich sein.", "tag": "Klimawandel" },
{ "question": "Der Bund soll mehr Zuständigkeiten in der Schulpolitik erhalten.", "tag": "Bildungspolitik" },
{ "question": "Der Bund soll Projekte zur Bekämpfung des Antisemitismus stärker finanziell unterstützen.", "tag": ["Antisemitismus", "Minderheitenpolitik"] },
{ "question": "Chinesische Firmen sollen keine Aufträge für den Ausbau der Kommunikationsinfrastruktur in Deutschland erhalten dürfen.", "tag": "Wirtschaftspolitik" },
{ "question": "Der Staat soll weiterhin für Religionsgemeinschaften die Kirchensteuer einziehen.", "tag": "Kirchensteuer" },
{ "question": "Der kontrollierte Verkauf von Cannabis soll generell erlaubt sein.", "tag": "Drogenpolitik" },
{ "question": "Deutschland soll aus der Europäischen Union austreten.", "tag": "EU-Politik" },
{ "question": "Die Landeslisten der Parteien für die Wahlen zum Deutschen Bundestag sollen abwechselnd mit Frauen und Männern besetzt werden müssen.", "tag": ["Geschlechtergerechtigkeit", "Minderheitenpolitik"] },
{ "question": "Stationäre Behandlungen im Krankenhaus sollen weiterhin über eine Fallpauschale abgerechnet werden.", "tag": "Gesundheitspolitik" },
{ "question": "Auf hohe Vermögen soll wieder eine Steuer erhoben werden.", "tag": ["Steuerpolitik", "Vermögenssteuer"] },
{ "question": "Bei der Videoüberwachung öffentlicher Plätze soll Gesichtserkennungssoftware eingesetzt werden dürfen.", "tag": ["Datenschutz", "Videoüberwachung"] },
{ "question": "Auch Ehepaare ohne Kinder sollen weiterhin steuerlich begünstigt werden.", "tag": "Familienpolitik" },
{ "question": "Ökologische Landwirtschaft soll stärker gefördert werden als konventionelle Landwirtschaft.", "tag": "Klimawandel" },
{ "question": "Islamische Verbände sollen als Religionsgemeinschaften staatlich anerkannt werden können.", "tag": ["Religionspolitik", "Minderheitenpolitik"] },
{ "question": "Der staatlich festgelegte Preis für den Ausstoß von CO2 beim Heizen und Autofahren soll stärker steigen als geplant.", "tag": ["Klimaschutz", "Klimawandel"] },
{ "question": "Die Schuldenbremse im Grundgesetz soll beibehalten werden.", "tag": "Wirtschaftspolitik" },
{ "question": "Asyl soll weiterhin nur politisch Verfolgten gewährt werden.", "tag": "Migrationspolitik" },
{ "question": "Der gesetzliche Mindestlohn sollte erhöht werden.", "tag": "Sozialpolitik" },
{ "question": "Der Flugverkehr soll höher besteuert werden.", "tag": ["Flugverkehr", "Klimapolitik"] },
{ "question": "Unternehmen sollen selbst entscheiden, ob sie ihren Beschäftigten das Arbeiten im Homeoffice erlauben.", "tag": ["Arbeitsrecht", "Digitalisierung"] }
]

0 comments on commit d882553

Please sign in to comment.