Untitled

 avatar
unknown
plain_text
a year ago
31 kB
5
Indexable
const express = require('express');
const { Telegraf, Scenes, session} = require('telegraf');
const { MongoClient } = require('mongodb');
const axios = require('axios');
const { CronJob } = require('cron');
const app = express();
const token = "6759891586:AAFJ-jxw7-8DVWrkiblx1QVACNj3OaiOYYk";
const bot = new Telegraf(token);
const { Stage, BaseScene, WizardScene } = Scenes;
const mongoURL = 'mongodb+srv://judgetorres:judgetorres1234@judgetorres.64yjcqg.mongodb.net/?retryWrites=true&w=majority';
process.on('uncaughtException', (error) => {
    console.error('Uncaught Exception:', error);
  });
  
const client = new MongoClient(mongoURL);
let db, stark;

// CONFIGMENT OF THE TWITTER API

const bearerToken = 'AAAAAAAAAAAAAAAAAAAAAF2esAEAAAAA6YgKnoonlVuvnxy6PVwzUeSFCnE%3DehHWdCbfdZ8O48u0XpbvElljT8LTOwlitntlldI4pe2ILRab5l';
const apiKey = 'pM2dGlCG77SgsRNo6HjAK00ul';
const apiSecretKey = 'boNFiHzxdHzHOdW4A6CFGriYEnFOARr37g3Jro6B4lfJy05cUb';
const accessToken = '1655168769361170433-vKDZKSjnoGAXx0NSRSNFUOVom0Z9wx';
const accessTokenSecret = 'COykXJICCojzTODhvHe4aAgCN9z7GQN41VWBVhoAOcuud';
const adminTwitterUsername = "1303216614515585027";
const tweetId = '1599222382417231872';
const tokenConfig = {
  auth: {
    username: apiKey,
    password: apiSecretKey,
  },
};
const config = {
  headers: {
    Authorization: `Bearer ${bearerToken}`,
  },
};
axios.post('https://api.twitter.com/oauth2/token', 'grant_type=client_credentials', tokenConfig)
  .then(console.log("Twitter Auth Authenticated"))
  .catch(err => console.log(err));


// get user twitter id

async function getUserTwitterId(username) {
   const url = `https://api.twitter.com/2/users/by/username/${username}`;
  try {
     const res = await axios.get(url, config);
    console.log(res.data);
    return res.data.data.id;
  } catch (err) {
    console.error(err.message);
     return null;
  }
}
 //


// get if user is following me 

/*async function isUserFollowingMe(username){

  const getAccessToken = async () => {
    try {
        const resp = await axios.post(
            'https://api.twitter.com/oauth2/token',
            '',
            {
                params: {
                    'grant_type': 'client_credentials'
                },
                auth: {
                    username: apiKey,
                    password: apiSecretKey
                }
            }
        );
        return resp.data.access_token
    } catch (err) {
        console.error(err);
        return;
    }
  };

  const getFollowers = async (token, user_id, max_number) => {
    try {
        const resp = await axios.get(
            `https://api.twitter.com/2/users/${user_id}/followers`,
            {
                headers: {
                    'Authorization': 'Bearer '+ token,
                },
                params: {
                    'user.fields': 'name,username',
                    'max_results': max_number
                }
            }
        );
        return resp.data;
    } catch (err) {
      console.log(err)
        return err
    }
  };

  getAccessToken()
    .then((token) => {
        getFollowers(token, adminTwitterUsername, 1000)
            .then((result) => {
                console.log(JSON.stringify(result, null, 4));
            })
            .catch(error => console.log(JSON.stringify(error)));
    })
    .catch(error => console.log(JSON.stringify(error)));
}*/
//



// END OF THE TWITTER API

//isUserFollowingMe("kingstarofficia");
//getUserTwitterId("kingstarofficia");

bot.use(session());
const stage = new Stage();
bot.use(stage.middleware());
const admin = 6354552851;
const cur = "points"
async function connectToDatabase(){
  try {
     await client.connect();
     db = await client.db('CEOAKDBOT');
     stark = await db.collection("All-Users");
    console.log(`Connected to database`);
  } catch (err) {
     console.log(`Error connect database`);
    console.log(err);
  }

}
connectToDatabase(true);

const channels = [
  "cartmoreelogs",
  "cartmoreelogs"
]

async function getUser(user) {
   try {
      const u = await stark.findOne({user: user});
     return u;
   } catch (err) {
      console.log(err);
     return null;
   }
}

async function addUser(user){
  try {
     await stark.insertOne(user);
    return true;
  } catch (err) {
    console.log(err)
     return null;
  }
}


async function updateUser(user,data){
  try {
     const res = await stark.updateOne({user: user},data);
    return true;
  } catch (err) {
    console.log(err)
     return null;
  }
}

async function allUser() {

   try {
      const res = await stark.find({}).toArray();
     return res;
   } catch (err) {
     console.log(err)
      return null;
   }

}

async function updateLeaderboard(interval) {

  function getStartDate(daysAgo) {
      const startDate = new Date();

  startDate.setDate(startDate.getDate() - daysAgo);

      return startDate;
    }

    const startDate = getStartDate(interval === 'daily' ? 1 : interval === 'weekly' ? 7 : 30);
    const endDate = new Date();

    const users = await stark.find({referral: {$gte: 1},lastReferralTime: {$gte: startDate,$lt: endDate}}).toArray();
    const count = 15;
    if(!users){
      console.log("No Users found in the "+interval+" contest");
      return;
    }
    if(users.length === 0){
      console.log("No Users found in the "+interval+" contest");
      return;
    }
    const userr = await users.sort((a,b) => b.referral - a.referral);

  const pointEarned = interval === 'daily' ? 50000 : interval === 'weekly' ? 100000 : 200000;

  const winner = await userr[0];
  updateUser(winner.user,{$inc: {balance: pointEarned}});
  const winner2 = await userr[1];
  const winner3 = await userr[2];

  const winnerAdminText = `
<b>πŸŽ‰ Congratulations to the winners of the ${interval} contest! πŸŽ‰</b>

<b>πŸ† Winner:</b> (${winner.user})
πŸ’° Reward: ${pointEarned} points


<b>πŸŽ‰ Congratulations to the the winners! πŸŽ‰</b>

<i>Winner: (${winner.user}) has get ${pointEarned} points added to his/her balance.</i>
`;

    const winnerUserText = `
<b>πŸŽ‰ Congratulations to you, </b>πŸ† You <b>won </b>the ${interval} contest! πŸŽ‰

<b>πŸ’° Reward:</b> ${pointEarned} points.
  `;

  if (winner){
    bot.telegram.sendMessage(winner.user,winnerUserText,{parse_mode: 'HTML'});
  }
  bot.telegram.sendMessage(admin,winnerAdminText,{parse_mode: 'HTML'});
}

function setupCronJobs() {
  const dailyJob = new CronJob('0 0 * * *', () => updateLeaderboard('daily'), null, true, 'UTC');
  const weeklyJob = new CronJob('0 0 * * 1', () => updateLeaderboard('weekly'), null, true, 'UTC');
  const monthlyJob = new CronJob('0 0 1 * *', () => updateLeaderboard('monthly'), null, true, 'UTC');
  dailyJob.start();
  weeklyJob.start();
  monthlyJob.start();
  console.log('Leaderboard Contest Started');
}

async function mainMenu(ctx,txt = null) {
   const text = `
${txt || ''}

πŸ‘‹πŸ» Hello Mr. <b>${ctx.from.first_name}</b>! Welcome To Our Bot (${ctx.botInfo.first_name})

πŸ† Your position on the airdrop bot are not final, and the valid participants will be <b>rewarded</b> if they are among the top referrers or random winners.

<i>πŸ“Œ You can use the buttons below to check your balance, Check The Leaderboard, and find useful.</i>

πŸ”— <b>Official Website:</b> <i>https://dontbuythistoken.com</i>
πŸ†˜ <b>For Support Contact:</b> <a href="https://t.me/CEOAKD365">Official Support</a>
`;

  const keys = [
    [
      {
        text: "πŸ’Ά Points Earned"
      }
    ],
    [
      {
        text: "πŸ‘©β€πŸ‘§β€πŸ‘¦ Referral"
      },
      {
        text: "πŸ’³ Claim"
      }
    ],
    [
      {
        text: "πŸ† Leaderboard"
      }
    ]
  ]
  ctx.reply(text, {
    parse_mode: "HTML",
    reply_markup: {
      keyboard: keys,
      resize_keyboard: true
    },
    disable_web_page_preview: true
  });
}


  bot.start(async (ctx) => { 

    const userId = ctx.from.id;
    const name = ctx.from.first_name || "Boss 😎"
    const newUser = await getUser(userId);
    if (newUser && newUser.verify && newUser.verify === true){
      mainMenu(ctx);
      return;
    }
    let upline = null;
    let param = ctx.message.text.split(" ");
    let [, ...newparam ] = param;


    if (!Array.isArray(newparam)){
      ctx.reply("🀯 Sorry, An error occured");
      return;
    }

    newparam = newparam[0] || "nothing";

    if (!newparam.includes('newUser')){

      if (!isNaN(newparam) && newparam.length === 10 && newparam != userId){
        upline = newparam;
      }
      if (!newUser){

        addUser({
          user: userId,
          upline: upline,
          balance: 0,
          demoWallet: null,
          verifyWallet: null,
          referral: 0,
          downlines: [],
          last_bonus_time: null,
          verify: false,
          ban: false
        });
        }

      ctx.reply('πŸ‘‹πŸ» Hi '+name+'!, Welcome to the bot!',{
        reply_markup: {
          inline_keyboard: [
            [
              {
                text: "✍🏻 Register on Website",
                web_app: {
                  url: "https://starknil.000webhostapp.com/ceoakdbot.html"
              }
              }
            ]
          ]
        }
      });  

      return;
    }
    if (!newparam.startsWith('newUser')){
      ctx.reply(JSON.stringify(more.length));
      ctx.reply("🀯 Sorry, An error occured 2");
      return;
    }
    const more = newparam.split("_");
    if (more.length !== 3){
      ctx.reply("🀯 Sorry, An error occured 3");
      return;
    }

    let [ ourUser, isVerify, wallet] = more;
    isVerify = isVerify.split("=")[1];
    wallet = wallet.split("=")[1];

    if (isVerify !== "true"){
      ctx.reply("Invalid Registration");
      return;
    }

    await updateUser(userId,{$set: {demoWallet: wallet}})

    const txt = "πŸ‘‹πŸ» Hi "+name+"!, Join our channels now!";

    const keyboards = [];

    for (const chan of channels){
      keyboards.push([
        {
          text: "πŸ”— Join "+chan,
          url: "https://t.me/"+chan
        }
      ]);
    }
    keyboards.push([
      {
        text: "βœ… Joined",
        callback_data: "chckchan"
      }
    ])

    ctx.reply(txt, {
      reply_markup: {
        inline_keyboard: keyboards
      }
    });
});

//////// Check mandatory channels

bot.action("chckchan", async (ctx) =>{
  const msg_id = ctx.update.callback_query.message.message_id;

  const userId = ctx.from.id;
  let c = 0;

  for (const channel of channels){
    try {
      const res = await ctx.telegram.getChatMember(`@${channel}`, userId);
      if(res.status == "left"){
        break;
      }else{
        c++
      }
    } catch (err) {
      ctx.answerCbQuery();
      ctx.reply("An error occurred while checking the channel membership. Please try again later.");
      console.log(err)
      return;
    }
  }

  if (channels.length != c){
    ctx.answerCbQuery("❌ Sorry, please join the telegram groups",{show_alert: true});
    return;
  }

  const mine = await getUser(userId);
  if (!mine){
    ctx.reply("Cant find your account, please register first");
    return;
  }

  const upline = mine.upline;
  const mee = mine.mandatoryJoinGift;

  if (!mee){
    ctx.answerCbQuery("βœ… You Earned 10 points for joining",{show_alert: true});
    await updateUser(userId,{$set: {mandatoryJoinGift: true},$inc: {balance: 10}});
  }

  try {
     await ctx.answerCbQuery();
  } catch (err) {
    console.log(err)
  }
  const twiterLink = "https://x.com/dbtteth";
  ctx.editMessageText(`
- Follow, comment, like, and retweet a post ${twiterLink}: and send your Twitter username.
`);
  const twit = new BaseScene("twitter"+userId);
  twit.enter();
  twit.on('text',async ctx => {
    let tw = ctx.message.text;
    ctx.deleteMessage();
    if (tw.length < 5){      
       try {
          await ctx.telegram.editMessageText(userId,msg_id,null,"Provide a valid twiter username without @")
       } catch (error) {
         console.log(err)
          return error;
       }      
      return;
    }

    if (tw.startsWith("@")){
      tw = tw.slice(1);
    }
    const twid = await getUserTwitterId(tw);

    if(!twid){
      try {
          await ctx.telegram.editMessageText(userId,msg_id,null,"Invalid Twitter account")
        } catch (err) {
          console.log(err);
      }      
      return;
    }













    await ctx.scene.leave();
    updateUser(userId,{$set: {twitter: tw}});
   const userr = await getUser(userId);
    if (!userr){
      return;
    }
     const meee = userr.twiterGift;
     const demoWallet = userr.demoWallet;

    const upline = userr.upline;
    if (!meee){
     await ctx.telegram.editMessageText(userId,msg_id,null,"βœ… You earned 10 points.");
    }

    const walleti = new BaseScene("wallet"+userId);

    walleti.enter(ctx => {      ctx.telegram.editMessageText(userId,msg_id,null,"Now please provide us your ETH wallet address\nNote: Must be same as use on the bot website\n\nEnter <code>0x12345</code>",{parse_mode: "HTML"});
    });

    walleti.on('text',async (ctx) => {
      ctx.deleteMessage();
      const wallet = ctx.message.text;
      if (wallet != demoWallet){
        try {
           await ctx.telegram.editMessageText(userId,msg_id,null,"❌ Wallet address must be same as the wallet on the bot website");
        } catch (err) {
          console.log(err);
          ctx.reply("You deleted an expected message which caused a error, Please restart te bot again");
           return;
        }

        return;
      }
      await ctx.scene.leave();
      await updateUser(userId,{$set: {verifyWallet: wallet,verify: true}});

      try {
         await ctx.telegram.deleteMessage(userId,msg_id);
      } catch (err) {
         console.log(err);
      }

      if (upline){
        try {
           await updateUser(parseFloat(upline),{$inc: {referral: 1,balance: 5},$push: {downlines: userId},$set: {lastReferralTime: new Date()}});

           await ctx.telegram.sendMessage(parseFloat(upline),"βž• New refer just joined through your link\nyou earned 5 points");

        } catch (err) {
          console.log(err)
        }
      } 

      mainMenu(ctx,"<b>βœ… Congratulations, You are fully verified.</b>");

    });

    walleti.use(async ctx => {
      ctx.deleteMessage();
      try{
        await ctx.telegram.editMessageText(userId,msg_id,null,"Enter a valid ETH wallet address");
         }catch(err){
        console.log(err)
        return;
         }
    });

    stage.register(walleti);
    ctx.scene.enter("wallet"+userId);

  });
  twit.use(async (ctx) => {
    try {
       ctx.deleteMessage();
      await ctx.telegram.editMessageText(userId,msg_id,null,"Provide a valid twiter username")
    } catch (err) {
      console.log(err)
       return;
    }

  }); 
  stage.register(twit);
  ctx.scene.enter("twitter"+userId);
});


// Top Daily Earners Code

bot.hears('πŸ† Leaderboard',async ctx => {

  function getStartDate(daysAgo) {
    const startDate = new Date();

startDate.setDate(startDate.getDate() - daysAgo);

    return startDate;
  }

  const interval = 'Daily';
  const startDate = getStartDate(interval === 'Daily' ? 1 : interval === 'Weekly' ? 7 : 30);
  const endDate = new Date();

  const idd = await ctx.replyWithHTML("<i>πŸ† Started Gathering Leaderboard...</i>");
  const msg_id = idd.message_id;
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Gathering Leaderboard...</i>",{
    parse_mode: "HTML"
  });
  const users = await stark.find({referral: {$gte: 1},lastReferralTime: {$gte: startDate,$lt: endDate}}).toArray();
  const count = 15;
  if(!users){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  if(users.length === 0){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  const userr = await users.sort((a,b) => b.referral - a.referral);
  const userrs = await userr.slice(0,count);
  let txt = "<b>πŸ† Top "+count+" "+interval+" Leaderboard Users πŸ†</b>\n\n";
;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Started Forming Leaderboard...</i>",{
    parse_mode: "HTML"
  });

  const middle = Math.floor(userrs.length/2);
  let i = 1;
  for (const user of userrs){
    if (i == middle){
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Forming Leaderboard 50%...</i>",{
        parse_mode: "HTML"
      });
    }
    const userId = user.user;
    const referral = user.referral;
    const bal = user.balance;
    const details = await ctx.telegram.getChat(user.user);
    let tag;
    if (i === 1){
      tag = "πŸ₯‡";
    }else if (i === 2){
      tag = "πŸ₯ˆ";
    } else if (i === 3){
      tag = "πŸ₯‰";
    }else{
      tag = `  ${i}`;
    }
    if (details.id != 6287539358){
      txt += `${tag} β€’ <a href="tg://user?id=${details.id}">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
    }else{
      txt += `${tag} β€’ <a href="">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
  }
   i += 1;
  }

  txt += `
<b>Daily Rank:</b> 50,000 $DBTT ($98)
<b>Weekly Rank:</b> 100,000 $DBTT ($196)
<b>Monthly Rank:</b> 200,000 $DBTT ($392)

<i>By completing the airdrop tasks, you will earn points and climb the leaderboard. The top  leaderboard users will receive a bonus <b>$DBTT</b> reward at the end of the Dally,Weekly,Monthly</i>
`;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,txt,{
    parse_mode: "HTML",
    reply_markup: {
      inline_keyboard: [
        [
          {
            text: "πŸ† Weekly Leaderboard πŸ†",
            callback_data: "weeklyb"
          }
        ],
        [
          {
            text: "πŸ† Monthly Leaderboard πŸ†",
            callback_data: "monthlyb"
          }
        ]
      ]
    }
  });
});

// Top Weekly Earners Code

bot.action('weeklyb',async ctx => {

  function getStartDate(daysAgo) {
    const startDate = new Date();

startDate.setDate(startDate.getDate() - daysAgo);

    return startDate;
  }

  const interval = 'Weekly';
  const startDate = getStartDate(interval === 'Daily' ? 1 : interval === 'Weekly' ? 7 : 30);
  const endDate = new Date();

  const msg_id = ctx.update.callback_query.message.message_id;
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Gathering Leaderboard...</i>",{
    parse_mode: "HTML"
  });
  const users = await stark.find({referral: {$gte: 1},lastReferralTime: {$gte: startDate,$lt: endDate}}).toArray();
  const count = 15;
  if(!users){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  if(users.length === 0){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  const userr = await users.sort((a,b) => b.referral - a.referral);
  const userrs = await userr.slice(0,count);
  let txt = "<b>πŸ† Top "+count+" "+interval+" Leaderboard Users πŸ†</b>\n\n";
;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Started Forming Leaderboard...</i>",{
    parse_mode: "HTML"
  });

  const middle = Math.floor(userrs.length/2);
  let i = 1;
  for (const user of userrs){
    if (i == middle){
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Forming Leaderboard 50%...</i>",{
        parse_mode: "HTML"
      });
    }
    const userId = user.user;
    const referral = user.referral;
    const bal = user.balance;
    const details = await ctx.telegram.getChat(user.user);
    let tag;
    if (i === 1){
      tag = "πŸ₯‡";
    }else if (i === 2){
      tag = "πŸ₯ˆ";
    } else if (i === 3){
      tag = "πŸ₯‰";
    }else{
      tag = `  ${i}`;
    }
    if (details.id != 6287539358){
      txt += `${tag} β€’ <a href="tg://user?id=${details.id}">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
    }else{
      txt += `${tag} β€’ <a href="">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
  }
   i += 1;
  }

  txt += `
<b>Daily Rank:</b> 50,000 $DBTT ($98)
<b>Weekly Rank:</b> 100,000 $DBTT ($196)
<b>Monthly Rank:</b> 200,000 $DBTT ($392)

<i>By completing the airdrop tasks, you will earn points and climb the leaderboard. The top  leaderboard users will receive a bonus <b>$DBTT</b> reward at the end of the Dally,Weekly,Monthly</i>
`;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,txt,{
    parse_mode: "HTML",
    reply_markup: {
      inline_keyboard: [
        [
          {
            text: "πŸ† Monthly Leaderboard πŸ†",
            callback_data: "monthlyb"
          }
        ]
      ]
    }
  });
});


// Top Weekly Earners Code

bot.action('monthlyb',async ctx => {

  function getStartDate(daysAgo) {
    const startDate = new Date();

startDate.setDate(startDate.getDate() - daysAgo);

    return startDate;
  }

  const interval = 'Monthly';
  const startDate = getStartDate(interval === 'Daily' ? 1 : interval === 'Weekly' ? 7 : 30);
  const endDate = new Date();

  const msg_id = ctx.update.callback_query.message.message_id;
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Gathering Leaderboard...</i>",{
    parse_mode: "HTML"
  });
  const users = await stark.find({referral: {$gte: 1},lastReferralTime: {$gte: startDate,$lt: endDate}}).toArray();
  const count = 15;
  if(!users){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  if(users.length === 0){
    ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"No user have a referral in this Bot.",{
      parse_mode: "HTML"
    });
    return;
  }
  const userr = await users.sort((a,b) => b.referral - a.referral);
  const userrs = await userr.slice(0,count);
  let txt = "<b>πŸ† Top "+count+" "+interval+" Leaderboard Users πŸ†</b>\n\n";
;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Started Forming Leaderboard...</i>",{
    parse_mode: "HTML"
  });

  const middle = Math.floor(userrs.length/2);
  let i = 1;
  for (const user of userrs){
    if (i == middle){
ctx.telegram.editMessageText(ctx.from.id,msg_id,null,"<i>πŸ† Forming Leaderboard 50%...</i>",{
        parse_mode: "HTML"
      });
    }
    const userId = user.user;
    const referral = user.referral;
    const bal = user.balance;
    const details = await ctx.telegram.getChat(user.user);
    let tag;
    if (i === 1){
      tag = "πŸ₯‡";
    }else if (i === 2){
      tag = "πŸ₯ˆ";
    } else if (i === 3){
      tag = "πŸ₯‰";
    }else{
      tag = `  ${i}`;
    }
    if (details.id != 6287539358){
      txt += `${tag} β€’ <a href="tg://user?id=${details.id}">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
    }else{
      txt += `${tag} β€’ <a href="">${details.first_name || details.last_name}</a> - <b>${referral} points</b>\n`;
  }
   i += 1;
  }

  txt += `
<b>Daily Rank:</b> 50,000 $DBTT ($98)
<b>Weekly Rank:</b> 100,000 $DBTT ($196)
<b>Monthly Rank:</b> 200,000 $DBTT ($392)

<i>By completing the airdrop tasks, you will earn points and climb the leaderboard. The top  leaderboard users will receive a bonus <b>$DBTT</b> reward at the end of the Dally,Weekly,Monthly</i>
`;
  ctx.telegram.editMessageText(ctx.from.id,msg_id,null,txt,{
    parse_mode: "HTML",
    reply_markup: {
      inline_keyboard: [
        [
          {
            text: "πŸ† Weekly Leaderboard πŸ†",
            callback_data: "weeklyb"
          }
        ]
      ]
    }
  });
});


//////
bot.command('add',async (ctx) => {
  updateUser(ctx.from.id,{$set: {lastReferralTime: new Date()}});
});
//////

// Balance button code

bot.hears("πŸ’Ά Points Earned",async (ctx) => {
  const userId = ctx.from.id;
  const userr = await getUser(userId);
  if (!userr){
    ctx.reply("Cant find your account, please register first");
    return;
  }
  const referral = userr.referral;
  const bal = userr.balance;
  let txt;
  if (referral == 0){
    txt = "<s>Not in Leaderboard</s>";
  }else{
    const users = await stark.find({referral: {$gte: 0}}).toArray();
    const count = 10;
    if(!users){
      txt = "<s>Not in Leaderboard</s>";
      return;
    }
    if(users.length === 0){
      txt = "<s>Not in Leaderboard</s>";
      return;
    }
    const userr = await users.sort((a,b) => b.referral - a.referral);
    const userrs = await userr.slice(0,count);

      const check = userrs.some(x => x.user == userId);

    if (check){
      const c = userrs.findIndex(x => x.user == userId);

      txt = c+1+" in Leaderboard";

    }else{
      txt = "<s>Not in Leaderboard</s>";
    }
  }
  ctx.replyWithHTML(`
πŸ’Ά You have earned <b>${bal} points</b>. You have invited <b>${referral} user(s)</b>.

<b>πŸ† Your Position:</b> ${txt}

βœ… <u>Your Provided Data</u>

  πŸͺΏ <b>Twitter:</b> ${userr.twitter || "Not Provided"}
  πŸ’³ <b>Connected Address:</b>
  <code>${userr.verifyWallet}</code>

<i>πŸ’²The top referrals can each get more tokens.</i>
`);
});

// Referral button code

bot.hears("πŸ‘©β€πŸ‘§β€πŸ‘¦ Referral",async (ctx) => {
  const userId = ctx.from.id;
  const userr = await getUser(userId);
  if (!userr){
    ctx.reply("Cant find your account, please register first");
    return;
  }
  const upline = userr.upline;
  const referral = userr.referral;
  const bal = userr.balance;
  const downlines = userr.downlines;
  const refLink = "https://t.me/"+ctx.botInfo.username+"?start="+userId;
  let txt = `
<b>πŸ“’You invited ${referral} people and have a chance to get $10 in points tokens. </b>

<i>πŸ’²You can refer more to be in top referrals to qualify on the leaderboard and get a huge banefits.</i>

<b>πŸ”—referral link:</b> <i>${refLink}</i>
`;

  ctx.replyWithHTML(txt);
});

// Claim button code

bot.hears("πŸ’³ Claim",async (ctx) => {
  const userId = ctx.from.id;
  const userr = await getUser(userId);
  if (!userr){
    ctx.reply("Cant find your account, please register first");
    return;
  }
  const referral = userr.referral;
  const bal = userr.balance;
  const demoWallet = userr.demoWallet;
  const verifyWallet = userr.verifyWallet;
  let txt = `
<b>πŸŽ‰ Great news! You can now withdraw your earned points on our website.</b>

1) <i>Visit the link below.</i>
2) <i>Click on the <b>Claim Not Active</b>.</i>
3) <i>Choose your withdrawal option.</i>
4) <i>Confirm your request.</i>

<b>That's it! Your rewards will be on their way.</b>

πŸ₯° <i>Thank you for being a part of our community!</i>

<b>---</b>
`;

  ctx.reply(txt,{
    parse_mode: "HTML",
    reply_markup: {
      inline_keyboard: [
        [
          {
            text: "😍 Claim your points",
            url: "https://dontbuythistoken.com/claim"
          }
        ]
      ]
    }
  })
});

// ADMIN PART

    bot.command('Panel',async (ctx) => {
      if(ctx.from.id != admin){
         return;
       }
       const user = await allUser(ctx.from.id);
       const txt = `
πŸ‘‹πŸ» Hey <b>${ctx.from.first_name}</b>! Welcome to the admin panel.

<b>Total Users:</b> ${user.length < 1 ? "No User" : user.length}`;
      ctx.reply(txt,{
        parse_mode: "HTML",
        reply_markup: {
          inline_keyboard:  [
              [
                {
                  text: "πŸŽ™οΈ Send Broadcast",
                  callback_data: "broadcast"
                }
              ],
              [
                {
                  text: "πŸ”— Set/Change X.com link",
                  callback_data: "setlink"
                }
              ]
            ]
        }
      });
    });

    bot.action('broadcast',async (ctx) => {
      ctx.deleteMessage();
       if(ctx.from.id != admin){
         return;
       }
      await ctx.reply("Wait fetching all user in the database...");
      const all_user = await allUser(ctx.from.id);
      await ctx.reply("All user fetched successfully");
      const broad = new BaseScene('broad');
      broad.enter(ctx => {
        ctx.reply("Enter the message you want to send");
      });
      broad.on('text', async (ctx) => {
        await ctx.scene.leave();
        await ctx.reply("Broadcasting message to all users...");

        for (const user of all_user){
          try {
             await ctx.telegram.sendMessage(user.user,ctx.message.text);
          } catch (err) {
            console.log(err);
          }

        }

        ctx.reply("Message broadcasted successfully");

      });
      stage.register(broad);
      ctx.scene.enter('broad');
    });

/*
bot.command("ban",async ctx => {
  if(ctx.from.id != admin){
    return;
  }
  const userId = ctx.message.text.split(" ")[1];
  ctx.reply(""+userId+"");
  const user = await getUser(parseFloat(userId));
  if (!user){
    return ctx.reply("User not found");
  }
  await updateUser(parseFloat(userId),{$set: {ban: true}});
  ctx.reply("User banned successfully");
});



bot.command("unban",async ctx => {
  if(ctx.from.id != admin){
    return;
  }
  const userId = ctx.message.text.split(" ")[1];
  const user = await getUser(parseFloat(userId));
  if (!user){
    return ctx.reply("User not found");
  }
  await updateUser(parseFloat(userId),{$set: {ban: false}});
  ctx.reply("User unbanned successfully");
});
*/
bot.use(ctx => ctx.reply('πŸ€” Sorry, I don\'t understand that'));

app.get('/', (req, res) => {
  const html = `
  <!DOCTYPE html>
  <html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Verify Bot Stark Nil</title>
      <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        width: 100%;
        height: 50vh;
        font-family: Arial, sans-serif;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 15px;
      }
      button {
      padding: 10px;
      background-color: #4CAF50;
      color: white;
      border: 1px solid grey;
      border-radius: 5px;
      }
      </style>
  </head>
  <body>
      <h1>Verify Bot Stark Nil</h1>
      <button onclick="
      window.location.href= 'https://t.me/CEOAKDAirdrop_Bot?start=newUser_verify=true_wallet=0x12345';
      this.style.display = 'none';
      ">
        <h1>
          ➑️ Click To Redirect
        </h1>
      </button>
  </body>
  </html>
`;
  res.send(html);
});
bot.launch({dropPendingUpdates: true});
const port = 3000;
app.listen(port,async () => {
  await setupCronJobs();
  console.log(`Server is running on port ${port}`);
});
Leave a Comment