瀏覽代碼

string improvements

Joystream Stats 3 年之前
父節點
當前提交
aa5a8f4964

+ 10 - 23
community-contributions/joystreamtelegrambot/src/bot.ts

@@ -19,7 +19,7 @@ import { AccountId, Header } from "@polkadot/types/interfaces";
 // functions
 import * as announce from "./lib/announcements";
 import * as get from "./lib/getters";
-import { parseArgs, printStatus, passedTime, exit } from "./lib/util";
+import { parseArgs, printStatus, passedTime } from "./lib/util";
 import moment from "moment";
 
 const opts: Options = parseArgs(process.argv.slice(2));
@@ -53,8 +53,6 @@ client.on("message", async (msg) => {
   }
 });
 
-let lastHeartbeat: number = moment().valueOf();
-
 // send to telegram and discord
 const sendMessage = (msg: { tg: string; discord: string }, channel: any) => {
   if (msg.tg === "") return;
@@ -93,10 +91,13 @@ const main = async () => {
   let council: Council = { round: 0, last: "" };
   let blocks: Block[] = [];
   let lastEra = 0;
+  let timestamp = await get.timestamp(api);
+  let duration = 0;
+  let lastHeartbeat = timestamp;
   let lastBlock: Block = {
     id: 0,
-    duration: 6000,
-    timestamp: lastHeartbeat,
+    duration: 0,
+    timestamp: 0,
     stake: 0,
     noms: 0,
     vals: 0,
@@ -116,8 +117,6 @@ const main = async () => {
   let proposals: Proposals = { last: 0, current: 0, active: [], executing: [] };
   let lastProposalUpdate = 0;
 
-  if (opts.channel) channels[0] = await get.currentChannelId(api);
-
   if (opts.forum) {
     posts[0] = await get.currentPostId(api);
     threads[0] = await get.currentThreadId(api);
@@ -137,8 +136,8 @@ const main = async () => {
       const id = header.number.toNumber();
 
       if (lastBlock.id === id) return;
-      const timestamp = (await api.query.timestamp.now()).toNumber();
-      const duration = timestamp - lastBlock.timestamp;
+      timestamp = await get.timestamp(api);
+      duration = lastBlock.timestamp ? timestamp - lastBlock.timestamp : 0;
 
       // update validators and nominators every era
       const era = Number(await api.query.staking.currentEra());
@@ -174,7 +173,7 @@ const main = async () => {
         reward,
         issued,
       };
-      blocks = blocks.concat(block);
+      if (duration) blocks = blocks.concat(block);
 
       // heartbeat
       if (timestamp > lastHeartbeat + heartbeat) {
@@ -201,18 +200,6 @@ const main = async () => {
           discordChannels.council
         );
 
-      if (opts.channel) {
-        channels[1] = await get.currentChannelId(api);
-        if (channels[1] > channels[0])
-          announce.channels(
-            api,
-            channels,
-            sendMessage,
-            discordChannels.channels
-          );
-        channels[0] = channels[1];
-      }
-
       if (opts.proposals) {
         proposals.current = await get.proposalCount(api);
 
@@ -245,5 +232,5 @@ const main = async () => {
 };
 main().catch((error) => {
   console.log(error);
-  exit(log);
+  process.exit();
 });

+ 5 - 4
community-contributions/joystreamtelegrambot/src/lib/announcements.ts

@@ -224,7 +224,7 @@ export const proposals = async (
       .format("DD/MM/YYYY HH:mm");
     const link = `${domain}/#/proposals/${id}`;
     const tg = `<a href="${link}">Proposal ${id}</a> <b>created</b> at block ${createdAt}.\r\n${message.tg}\r\nYou can <a href="${link}">vote</a> until block ${votingEndsAt} (${endTime} UTC).`;
-    const discord = `Proposal ${id} **created** at block ${createdAt}. ${message.discord}\nVote until block ${votingEndsAt} (${endTime} UTC): ${link}`;
+    const discord = `Proposal ${id} **created** at block ${createdAt}.\n${message.discord}\nVote until block ${votingEndsAt} (${endTime} UTC): ${link}\n`;
     sendMessage({ tg, discord }, channel);
     active.push(id);
   }
@@ -241,7 +241,7 @@ export const proposals = async (
       }
       const link = `${domain}/#/proposals/${id}`;
       const tg = `<a href="${link}">Proposal ${id}</a> <b>${label}</b> at block ${finalizedAt}.\r\n${message.tg}`;
-      const discord = `Proposal ${id} **${label}** at block ${finalizedAt}.\n${message.discord}\n${link}`;
+      const discord = `Proposal ${id} **${label}** at block ${finalizedAt}.\n${message.discord}\n${link}\n`;
       sendMessage({ tg, discord }, channel);
       active = active.filter((a) => a !== id);
     }
@@ -254,7 +254,7 @@ export const proposals = async (
     if (block < executesAt) continue;
     const link = `${domain}/#/proposals/${id}`;
     const tg = `<a href="${link}">Proposal ${id}</a> <b>executed</b> at block ${executesAt}.\r\n${message.tg}`;
-    const discord = `Proposal ${id} **executed** at block ${executesAt}.\n${message.discord}\n${link}`;
+    const discord = `Proposal ${id} **executed** at block ${executesAt}.\n${message.discord}\n${link}\n`;
     sendMessage({ tg, discord }, channel);
     executing = executing.filter((e) => e !== id);
   }
@@ -278,6 +278,7 @@ export const heartbeat = async (
   const price = await fetchTokenValue();
   const storageSize = await fetchStorageSize();
   const durations = blocks.map((b) => b.duration);
+  console.log(durations);
   const blocktime = getAverage(durations) / 1000;
 
   const stake = blocks.map((b) => b.stake);
@@ -299,7 +300,7 @@ export const heartbeat = async (
   let proposalString: string[] = pending
     ? [
         `<a href="${domain}/#/proposals">${pending} pending ${p(pending)}</a> `,
-        `${pending} pending ${p(pending)} ${domain}/#/proposals`,
+        `${pending} active ${p(pending)} ${domain}/#/proposals`,
       ]
     : ["", ""];
   if (finalized)

+ 16 - 7
community-contributions/joystreamtelegrambot/src/lib/getters.ts

@@ -14,9 +14,10 @@ import { Category, CategoryId } from "@joystream/types/forum";
 import { MemberId, Membership } from "@joystream/types/members";
 import { Proposal } from "@joystream/types/proposals";
 
-// channel
+// api
 
-export const currentChannelId = async (api: Api): Promise<number> => -1;
+export const timestamp = async (api: Api) =>
+  (await api.query.timestamp.now()).toNumber();
 
 export const memberHandle = async (api: Api, id: MemberId): Promise<string> => {
   const membership: Membership = await api.query.members.membershipById(id);
@@ -110,10 +111,18 @@ export const proposalDetail = async (
   return { createdAt, finalizedAt, parameters, message, stage, result, exec };
 };
 
-export const fetchTokenValue = async () => {
-  const { data } = await axios.get("https://status.joystream.org/status");
-  return data ? `${Math.floor(+data.price * 100000000) / 100} $` : `?`;
-};
+// status endpoint
+
+export const fetchTokenValue = async (): Promise<string> =>
+  axios
+    .get("https://status.joystream.org/status")
+    .then(({ data }) => `${Math.floor(+data.price * 100000000) / 100} $`)
+    .catch((e) => {
+      console.log(`Failed to fetch status.`);
+      return `?`;
+    });
+
+// hdyra
 
 export const fetchStorageSize = async () => {
   const dashboard = "https://analytics.dapplooker.com/api/public/dashboard";
@@ -121,6 +130,6 @@ export const fetchStorageSize = async () => {
 
   const { data } = await axios.get(`${dashboard}/${asset}`);
 
-  const size = Math.round(data.data.rows[0][0]) + "GB";
+  const size = Math.round(data.data.rows[0][0]) + " GB";
   return size;
 };

+ 0 - 5
community-contributions/joystreamtelegrambot/src/lib/util.ts

@@ -55,8 +55,3 @@ export const passedTime = (start: number, now: number): string => {
       : "mm:ss[m]";
   return formatTime(passed, format);
 };
-
-export const exit = (log: (s: string) => void) => {
-  log("\nNo connection, exiting.\n");
-  process.exit();
-};