Explorar el Código

send to discord

Joystream Stats hace 3 años
padre
commit
753a049fe2

+ 1 - 0
community-contributions/joystreamtelegrambot/package.json

@@ -24,6 +24,7 @@
   },
   "dependencies": {
     "@joystream/types": "^0.16.1",
+    "discord.js": "^12.5.3",
     "moment": "^2.29.1",
     "node-telegram-bot-api": "^0.51.0",
     "ws": "^7.4.1"

+ 82 - 9
community-contributions/joystreamtelegrambot/src/bot.ts

@@ -1,5 +1,13 @@
+import { Client } from "discord.js";
 import TelegramBot from "node-telegram-bot-api";
-import { token, chatid, heartbeat, proposalDelay, wsLocation } from "../config";
+import {
+  discordToken,
+  tgToken,
+  chatid,
+  heartbeat,
+  proposalDelay,
+  wsLocation,
+} from "../config";
 
 // types
 import { Block, Council, Options, Proposals } from "./types";
@@ -18,17 +26,53 @@ const log = (msg: string): void | number => opts.verbose && console.log(msg);
 process.env.NTBA_FIX_319 ||
   log("TL;DR: Set NTBA_FIX_319 to hide this warning.");
 
-const bot = token ? new TelegramBot(token, { polling: true }) : null;
+// connect to telegram
+const bot = tgToken ? new TelegramBot(tgToken, { polling: true }) : null;
+
+// connect to discord
+let discordChannels: { [key: string]: any } = {};
+const client = new Client();
+client.login(discordToken);
+client.on("ready", async () => {
+  if (!client.user) return;
+  console.log(`Logged in to discord as ${client.user.tag}!`);
+  discordChannels.council = await findDiscordChannel("council");
+  discordChannels.proposals = await findDiscordChannel("proposals-bot");
+  discordChannels.forum = await findDiscordChannel("forum-bot");
+});
+
+const findDiscordChannel = (name: string) =>
+  client.channels.cache.find((channel: any) => channel.name === name);
+
+client.on("message", async (msg) => {
+  const user = msg.author;
+  if (msg.content === "/status") {
+    msg.reply(`reporting to discord`);
+  }
+});
 
 let lastHeartbeat: number = moment().valueOf();
 
-const sendMessage = (msg: string) => {
+// send to telegram and discord
+const sendMessage = (msg: string, channel: any) => {
   if (msg === "") return;
+  sendDiscord(msg, channel);
+  sendTelegram(msg);
+};
+const sendTelegram = (msg: string) => {
   try {
     if (bot) bot.sendMessage(chatid, msg, { parse_mode: "HTML" });
     else console.log(msg);
   } catch (e) {
-    console.log(`Failed to send message: ${e}`);
+    console.log(`Failed to send to telegram: ${e}`);
+  }
+};
+const sendDiscord = (msg: string, channel: any) => {
+  if (!channel) return;
+  try {
+    channel.send(msg);
+  } catch (e) {
+    console.log(e);
   }
 };
 
@@ -132,18 +176,36 @@ const main = async () => {
       // heartbeat
       if (timestamp > lastHeartbeat + heartbeat) {
         const time = passedTime(lastHeartbeat, timestamp);
-        blocks = announce.heartbeat(api, blocks, time, proposals, sendMessage);
+        blocks = announce.heartbeat(
+          api,
+          blocks,
+          time,
+          proposals,
+          sendMessage,
+          discordChannels.proposals
+        );
         lastHeartbeat = block.timestamp;
       }
 
       // announcements
       if (opts.council && block.id > lastBlock.id)
-        council = await announce.council(api, council, block.id, sendMessage);
+        council = await announce.council(
+          api,
+          council,
+          block.id,
+          sendMessage,
+          discordChannels.council
+        );
 
       if (opts.channel) {
         channels[1] = await get.currentChannelId(api);
         if (channels[1] > channels[0])
-          channels[0] = await announce.channels(api, channels, sendMessage);
+          channels[0] = await announce.channels(
+            api,
+            channels,
+            sendMessage,
+            discordChannels.channels
+          );
       }
 
       if (opts.proposals) {
@@ -153,14 +215,25 @@ const main = async () => {
           (timestamp > lastProposalUpdate + 60000 * proposalDelay &&
             (proposals.active || proposals.executing))
         ) {
-          proposals = await announce.proposals(api, proposals, id, sendMessage);
+          proposals = await announce.proposals(
+            api,
+            proposals,
+            id,
+            sendMessage,
+            discordChannels.proposals
+          );
           lastProposalUpdate = timestamp;
         }
       }
 
       if (opts.forum) {
         posts[1] = await get.currentPostId(api);
-        posts[0] = await announce.posts(api, posts, sendMessage);
+        posts[0] = await announce.posts(
+          api,
+          posts,
+          sendMessage,
+          discordChannels.forum
+        );
       }
 
       printStatus(opts, { block: id, chain, posts, proposals });

+ 26 - 17
community-contributions/joystreamtelegrambot/src/lib/announcements.ts

@@ -5,6 +5,7 @@ import {
   Member,
   ProposalDetail,
   Proposals,
+  Send,
 } from "../types";
 import { BlockNumber } from "@polkadot/types/interfaces";
 import { Channel, ElectionStage } from "@joystream/types/augment";
@@ -35,7 +36,8 @@ const query = async (test: string, cb: () => Promise<any>): Promise<any> => {
 export const channels = async (
   api: Api,
   channels: number[],
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): Promise<number> => {
   const [last, current] = channels;
   const messages: string[] = [];
@@ -51,7 +53,7 @@ export const channels = async (
       `<b>Channel <a href="${domain}/#//media/channels/${id}">${id}</a> by <a href="${member.url}">${member.handle} (${member.id})</a></b>`
     );
   }
-  sendMessage(messages.join("\r\n\r\n"));
+  sendMessage(messages.join("\r\n\r\n"), channel);
   return current;
 };
 
@@ -61,7 +63,8 @@ export const council = async (
   api: Api,
   council: Council,
   currentBlock: number,
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): Promise<Council> => {
   const round: number = await api.query.councilElection.round();
   const stage: any = await api.query.councilElection.stage();
@@ -107,7 +110,7 @@ export const council = async (
     round !== council.round &&
     stageString !== council.last
   )
-    sendMessage(msg);
+    sendMessage(msg, channel);
   return { round, last: stageString };
 };
 
@@ -116,7 +119,8 @@ export const council = async (
 export const categories = async (
   api: Api,
   category: number[],
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): Promise<number> => {
   if (category[0] === category[1]) return category[0];
   const messages: string[] = [];
@@ -127,7 +131,7 @@ export const categories = async (
     messages.push(msg);
   }
 
-  sendMessage(messages.join("\r\n\r\n"));
+  sendMessage(messages.join("\r\n\r\n"), channel);
   return category[1];
 };
 
@@ -135,7 +139,8 @@ export const categories = async (
 export const posts = async (
   api: Api,
   posts: number[],
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): Promise<number> => {
   const [last, current] = posts;
   if (current === last) return last;
@@ -151,6 +156,9 @@ export const posts = async (
       api.query.forum.threadById(threadId)
     );
     const categoryId = thread.category_id.toNumber();
+    if (categoryId === 19 || categoryId === 38) continue; // hide: 19 Media, 38 Russian
+    if ([180, 265, 275].includes(threadId)) continue;
+    // 180 tokens, 265 faucet, 275 pets
 
     const category: Category = await query("title", () =>
       categoryById(api, categoryId)
@@ -170,7 +178,7 @@ export const posts = async (
     );
   }
 
-  sendMessage(messages.join("\r\n\r\n"));
+  sendMessage(messages.join("\r\n\r\n"), channel);
   return current;
 };
 
@@ -179,7 +187,8 @@ export const proposals = async (
   api: Api,
   prop: Proposals,
   block: number,
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): Promise<Proposals> => {
   let { current, last, active, executing } = prop;
 
@@ -191,7 +200,7 @@ export const proposals = async (
       .add(6 * (votingEndsAt - block), "second")
       .format("DD/MM/YYYY HH:mm");
     const msg = `Proposal ${id} <b>created</b> at block ${createdAt}.\r\n${message}\r\nYou can vote until ${endTime} UTC (block ${votingEndsAt}).`;
-    sendMessage(msg);
+    sendMessage(msg, channel);
     active.push(id);
   }
 
@@ -206,7 +215,7 @@ export const proposals = async (
         if (!executed) executing.push(id);
       }
       const msg = `Proposal ${id} <b>${label}</b> at block ${finalizedAt}.\r\n${message}`;
-      sendMessage(msg);
+      sendMessage(msg, channel);
       active = active.filter((a) => a !== id);
     }
   }
@@ -217,7 +226,7 @@ export const proposals = async (
     const executesAt = +finalizedAt + parameters.gracePeriod.toNumber();
     if (block < executesAt) continue;
     const msg = `Proposal ${id} <b>executed</b> at block ${executesAt}.\r\n${message}`;
-    sendMessage(msg);
+    sendMessage(msg, channel);
     executing = executing.filter((e) => e !== id);
   }
 
@@ -234,7 +243,8 @@ export const heartbeat = (
   blocks: Block[],
   timePassed: string,
   proposals: Proposals,
-  sendMessage: (msg: string) => void
+  sendMessage: Send,
+  channel: any
 ): [] => {
   const durations = blocks.map((b) => b.duration);
   const blocktime = getAverage(durations) / 1000;
@@ -261,15 +271,14 @@ export const heartbeat = (
   if (finalized)
     proposalString += `${finalized} ${p(finalized)} in grace period.`;
 
-  sendMessage(
-    `  ${blocks.length} blocks produced in ${timePassed}
+  const msg = `  ${blocks.length} blocks produced in ${timePassed}
   Blocktime: ${blocktime.toFixed(3)}s
   Stake: ${avgStake.toFixed(1)} / ${avgIssued.toFixed()} M tJOY (${percent}%)
   Validators: ${avgVals.toFixed()} (${reward} tJOY/h)
   Nominators: ${getAverage(noms).toFixed()}
-  ${proposalString}`
-  );
+  ${proposalString}`;
 
+  sendMessage(msg, channel);
   return [];
 };
 

+ 2 - 0
community-contributions/joystreamtelegrambot/src/types/index.ts

@@ -58,3 +58,5 @@ export interface Block {
   issued: number;
   reward: number;
 }
+
+export type Send = (msg: string, channel: any) => void;