Skip to content

Commit

Permalink
chore: no wallet fallback msg for payments
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Oct 26, 2024
1 parent dffec78 commit 7382674
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 103 deletions.
109 changes: 22 additions & 87 deletions src/bot/mtproto-api/bot/scripts/sms-auth/auth-handler.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
// @ts-expect-error no types for this package
import input from "input";
import dotenv from "dotenv";
import { createClient, SupabaseClient } from "@supabase/supabase-js";
import { BaseMtProto } from "./base-mtproto";
import { Context } from "../../../../../types";
import { logger } from "../../../../../utils/logger";
import { GithubStorage } from "../../../../../adapters/github/storage-layer";
import { Octokit } from "@octokit/rest";
dotenv.config();

/**
* The account holder must run this script (to my knowledge only once) to login,
* this will give us the necessary session information to login in the future.
*/
export class AuthHandler {
private _github: GithubStorage | undefined;
private _supabase: SupabaseClient | null = null;
private _env = {
TELEGRAM_API_HASH: null,
TELEGRAM_API_HASH: null as string | null,
TELEGRAM_APP_ID: 0,
TELEGRAM_BOT_TOKEN: null,
} as {
TELEGRAM_API_HASH: string | null;
TELEGRAM_APP_ID: number;
TELEGRAM_BOT_TOKEN: string | null;
TELEGRAM_BOT_TOKEN: null as string | null,
};

constructor() {
Expand All @@ -30,41 +25,20 @@ export class AuthHandler {
throw new Error("Have you ran the setup script? Try running 'yarn setup-env' first.");
}

const key = process.env.REPO_ADMIN_ACCESS_TOKEN;

if (!key) {
throw new Error("Missing Github PAT token.");
}

const owner = process.env.TELEGRAM_BOT_REPOSITORY_FULL_NAME?.split("/")[0];

if (!owner) {
throw new Error("Missing TELEGRAM_BOT_REPOSITORY_FULL_NAME");
}

this._github = new GithubStorage(
{
octokit: new Octokit({ auth: key }),
} as unknown as Context,
{
storageOwner: owner,
isEnvSetup: true,
}
);

const parsedEnv: Context["env"]["TELEGRAM_BOT_ENV"] = JSON.parse(env);
if (!parsedEnv) {
throw new Error("Failed to parse environment variables for Telegram Bot");
}

const { botSettings, mtProtoSettings } = parsedEnv;
const { botSettings, mtProtoSettings, storageSettings } = parsedEnv;

if (!botSettings || !mtProtoSettings) {
if (!botSettings || !mtProtoSettings || !storageSettings) {
throw new Error("Missing required environment variables for Telegram Bot settings");
}

const { TELEGRAM_BOT_TOKEN, TELEGRAM_BOT_WEBHOOK } = botSettings;
const { TELEGRAM_APP_ID, TELEGRAM_API_HASH } = mtProtoSettings;
const { SUPABASE_URL, SUPABASE_SERVICE_KEY } = storageSettings;

if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_BOT_WEBHOOK) {
throw new Error("Missing required environment variables for Telegram Bot settings");
Expand All @@ -74,6 +48,12 @@ export class AuthHandler {
throw new Error("Missing required environment variables for MtProto settings");
}

if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY) {
throw new Error("Missing required environment variables for storage settings");
}

this._supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);

this._env = {
TELEGRAM_API_HASH,
TELEGRAM_APP_ID,
Expand All @@ -92,73 +72,28 @@ export class AuthHandler {
* In that order and the code will be sent to a Telegram instance
* which the associated phone number is logged in.
*
* The session data will be saved to GitHub plugin storage for future use.
* The session data will be saved to Supabase for future use.
*/
async smsLogin() {
const env = process.env.TELEGRAM_BOT_ENV;
if (!env) {
throw new Error("Have you ran the setup script? Try running 'yarn setup-env' first.");
}

const key = process.env.REPO_ADMIN_ACCESS_TOKEN;

if (!key) {
throw new Error("Missing Github PAT token.");
}

const owner = process.env.TELEGRAM_BOT_REPOSITORY_FULL_NAME?.split("/")[0];

if (!owner) {
throw new Error("Missing TELEGRAM_BOT_REPOSITORY_FULL_NAME");
}

this._github = new GithubStorage(
{
octokit: new Octokit({ auth: key }),
} as unknown as Context,
{
storageOwner: owner,
isEnvSetup: true,
}
);

const mtProto = new BaseMtProto();

if (this._env.TELEGRAM_API_HASH === null) {
throw new Error("Missing required environment variables for Telegram API");
}

if (this._env.TELEGRAM_APP_ID === 0) {
throw new Error("Missing required environment variables for Telegram API");
}

if (this._env.TELEGRAM_BOT_TOKEN === null) {
throw new Error("Missing required environment variables for Telegram API");
// empty string as it's a new session
if (!this._env.TELEGRAM_API_HASH || !this._env.TELEGRAM_APP_ID) {
throw new Error("Missing required environment variables for MtProto settings");
}

const envObj = {
TELEGRAM_API_HASH: this._env.TELEGRAM_API_HASH,
TELEGRAM_APP_ID: this._env.TELEGRAM_APP_ID,
TELEGRAM_BOT_TOKEN: this._env.TELEGRAM_BOT_TOKEN,
};

await mtProto.initialize(envObj);
await mtProto.initialize(this._env as Context["env"]["TELEGRAM_BOT_ENV"]["mtProtoSettings"], "");
try {
await mtProto.client?.start({
phoneNumber: async () => await input.password("Enter your phone number:"),
phoneNumber: async () => await input.text("Enter your phone number:"),
password: async () => await input.password("Enter your password if required:"),
phoneCode: async () => await input.text("Enter the code you received:"),
onError: (err: unknown) => console.error("Error during login:", { err }),
});

if (!mtProto.session) {
throw new Error("Failed to get session data.");
}

const didSave = await this._github.handleSession(mtProto.session.save(), "create");
const data = await this._supabase?.from("tg-bot-sessions").insert([{ session_data: mtProto.session?.save() }]);

if (!didSave) {
throw new Error("Failed to save session data to GitHub.");
if (data?.error) {
throw new Error("Failed to save session data to Supabase.");
}

logger.ok("Successfully logged in and saved session data. You can now run the bot.");
Expand Down
53 changes: 38 additions & 15 deletions src/handlers/private-notifications/comment-triggers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { logger } from "../../utils/logger";

const reminderCommentRegex = /@(\w+), this task has been idle for a while. Please provide an update./gi;
// eslint-disable-next-line sonarjs/duplicates-in-character-class
const base64ClaimUrlRegex = /href="https:\/\/[^/]+\/?\?claim=([A-Za-z0-9+/=])"/gi;
const base64ClaimUrlRegex = /href="https:\/\/[^/]+\/?\?claim=([A-Za-z0-9+/=]+)"/gi;
const amountPatternRegex = /\[\s*\d+(\.\d+)?\s*[A-Z]+\s*\]/gi;
// eslint-disable-next-line sonarjs/duplicates-in-character-class
const githubUsernameRegex = /<h6>@([a-zA-Z0-9-]{1,39})<\/h6>/gi;
Expand Down Expand Up @@ -69,6 +69,7 @@ export async function notificationsRequiringComments(context: Context<"issue_com
const { payload } = context;
const { body } = payload.comment;
const { results, users } = await getUsersFromStorage(context, body);

const bot = (await TelegramBotSingleton.initialize(context.env)).getBot();

const commentDependantTriggers = ["payment", "reminder"];
Expand Down Expand Up @@ -107,10 +108,10 @@ async function handleCommentNotificationTrigger({
context: Context<"issue_comment.created" | "issue_comment.edited">;
claimUrl?: string;
}) {
if (trigger === "reminder") {
if (trigger === "reminder" && !claimUrl) {
return handleReminderNotification(user.github_username, telegramId, bot, context);
} else if (trigger === "payment") {
return handlePaymentNotification(user.github_username, claimUrl, telegramId, bot);
return handlePaymentNotification(user, claimUrl, telegramId, bot, context);
}
}

Expand Down Expand Up @@ -146,20 +147,32 @@ This task has been idle for a while, please provide an update on <a href="${cont
return { status: 200, reason: "success" };
}

async function handlePaymentNotification(username: string, claimUrlBase64String: string | undefined, telegramId: string | number, bot: Bot) {
if (!claimUrlBase64String) {
logger.error(`Claim URL not found for ${username}`);
return;
}
const message = `<b>Hello ${username.charAt(0).toUpperCase() + username.slice(1)}</b>,
🎉 A task reward has been generated for you 🎉
async function handlePaymentNotification(
user: StorageUser,
claimUrlBase64String: string | undefined,
telegramId: string | number,
bot: Bot,
context: Context<"issue_comment.created" | "issue_comment.edited">
) {
const { wallet_address, github_username: username } = user;
if (!wallet_address) {
logger.error(`Wallet address not found for ${username}`);
const noWalletMessage = `<b>Hello ${username.charAt(0).toUpperCase() + username.slice(1)}</b>,
You can claim your reward by clicking the link below:
It seems you are subscribed to payment notifications and may have received a payment. However, we couldn't find a registered wallet address for you.
Please use the \`/wallet\` command to set your wallet address for future notifications.
<a href="https://pay.ubq.fi?claim=${claimUrlBase64String}">Claim Your Reward</a>
You can view the comment <a href="${context.payload.comment.html_url}">here</a>.
`;

Thank you for your contribution.`;
try {
await bot?.api.sendMessage(Number(telegramId), noWalletMessage, { parse_mode: "HTML" });
} catch (er) {
logger.error(`Error sending message to ${telegramId}`, { er });
}
return;
}

let userPrivateChat;

Expand All @@ -174,8 +187,18 @@ Thank you for your contribution.`;
return;
}

const notificationMessage = `<b>Hello ${username.charAt(0).toUpperCase() + username.slice(1)}</b>,
🎉 A task reward has been generated for you 🎉
You can claim your reward by clicking the link below:
<a href="https://pay.ubq.fi?claim=${claimUrlBase64String}">Claim Your Reward</a>
Thank you for your contribution.`;

try {
await bot?.api.sendMessage(Number(telegramId), message, { parse_mode: "HTML" });
await bot?.api.sendMessage(Number(telegramId), notificationMessage, { parse_mode: "HTML" });
} catch (er) {
logger.error(`Error sending message to ${telegramId}`, { er });
}
Expand Down
1 change: 0 additions & 1 deletion src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export default {

if (["/telegram", "/telegram/"].includes(path)) {
try {
console.log("TOUCHING TELEGRAM");
await TelegramBotSingleton.initialize(envSettings);
return await handleTelegramWebhook(request, envSettings);
} catch (err) {
Expand Down

0 comments on commit 7382674

Please sign in to comment.