From fb74173bf806abd8f59a32c28180a84b78e5480d Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Tue, 20 Jul 2021 20:23:20 +0000 Subject: [PATCH 01/12] upgrade joystream types to 0.16.1 --- .../joystreamtelegrambot/package.json | 2 +- .../joystreamtelegrambot/src/bot.ts | 10 +++++++--- .../joystreamtelegrambot/src/lib/announcements.ts | 6 +++--- .../joystreamtelegrambot/src/lib/getters.ts | 5 +---- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/package.json b/community-contributions/joystreamtelegrambot/package.json index 939861647..fbd20c9c4 100644 --- a/community-contributions/joystreamtelegrambot/package.json +++ b/community-contributions/joystreamtelegrambot/package.json @@ -23,12 +23,12 @@ "tests": "ts-node src/tests.ts" }, "dependencies": { + "@joystream/types": "^0.16.1", "moment": "^2.29.1", "node-telegram-bot-api": "^0.51.0", "ws": "^7.4.1" }, "devDependencies": { - "@joystream/types": "^0.15.0", "@types/node-telegram-bot-api": "^0.51.0", "ts-node": "^9.0.0", "ts-node-dev": "^1.0.0-pre.63", diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index 4a2d06374..fcd34adb3 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -42,6 +42,7 @@ const main = async () => { api.rpc.system.name(), api.rpc.system.version(), ]); + log(`Subscribed to ${chain} on ${node} v${version}`); let council: Council = { round: 0, last: "" }; let blocks: Block[] = []; @@ -83,11 +84,11 @@ const main = async () => { const getReward = async (era: number) => Number(await api.query.staking.erasValidatorReward(era)); - log(`Subscribed to ${chain} on ${node} v${version}`); api.rpc.chain.subscribeNewHeads( async (header: Header): Promise => { // current block const id = header.number.toNumber(); + if (lastBlock.id === id) return; const timestamp = (await api.query.timestamp.now()).toNumber(); const duration = timestamp - lastBlock.timestamp; @@ -163,8 +164,11 @@ const main = async () => { } printStatus(opts, { block: id, chain, posts, proposals }); - lastBlock = block + lastBlock = block; } ); }; -main().catch(() => exit(log)); +main().catch((error) => { + console.log(error); + exit(log); +}); diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 762f9a5e3..3ba0f6753 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -44,11 +44,11 @@ export const channels = async ( const channel: Channel = await query("title", () => api.query.contentWorkingGroup.channelById(id) ); - const member: Member = { id: channel.owner, handle: "", url: "" }; - member.handle = await memberHandle(api, member.id.toJSON()); + const member: Member = { id: channel.owner.asMember, handle: "", url: "" }; + member.handle = await memberHandle(api, member.id); member.url = `${domain}/#/members/${member.handle}`; messages.push( - `Channel ${channel.title} by ${member.handle} (${member.id})` + `Channel ${id} by ${member.handle} (${member.id})` ); } sendMessage(messages.join("\r\n\r\n")); diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index ad4a034fe..f2e975445 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/getters.ts @@ -15,10 +15,7 @@ import { Proposal } from "@joystream/types/proposals"; // channel -export const currentChannelId = async (api: Api): Promise => { - const id: ChannelId = await api.query.contentWorkingGroup.nextChannelId(); - return id.toNumber() - 1; -}; +export const currentChannelId = async (api: Api): Promise => -1 export const memberHandle = async (api: Api, id: MemberId): Promise => { const membership: Membership = await api.query.members.membershipById(id); From 753a049fe25b7582243e3f61f0c087ec42e650b2 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Tue, 20 Jul 2021 22:09:25 +0000 Subject: [PATCH 02/12] send to discord --- .../joystreamtelegrambot/package.json | 1 + .../joystreamtelegrambot/src/bot.ts | 91 +++++++++++++++++-- .../src/lib/announcements.ts | 43 +++++---- .../joystreamtelegrambot/src/types/index.ts | 2 + 4 files changed, 111 insertions(+), 26 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/package.json b/community-contributions/joystreamtelegrambot/package.json index fbd20c9c4..5e268081d 100644 --- a/community-contributions/joystreamtelegrambot/package.json +++ b/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" diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index fcd34adb3..2b04b864d 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/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 }); diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 3ba0f6753..5365003ac 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/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): Promise => { export const channels = async ( api: Api, channels: number[], - sendMessage: (msg: string) => void + sendMessage: Send, + channel: any ): Promise => { const [last, current] = channels; const messages: string[] = []; @@ -51,7 +53,7 @@ export const channels = async ( `Channel ${id} by ${member.handle} (${member.id})` ); } - 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 => { 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 => { 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 => { 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 => { 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} created 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} ${label} 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} executed 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 []; }; diff --git a/community-contributions/joystreamtelegrambot/src/types/index.ts b/community-contributions/joystreamtelegrambot/src/types/index.ts index 42fbff849..4b25b32bc 100644 --- a/community-contributions/joystreamtelegrambot/src/types/index.ts +++ b/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; From 4e4a423046b3285597f08343bc37ae2279f63a87 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Thu, 22 Jul 2021 15:34:35 +0000 Subject: [PATCH 03/12] strip html for discord --- community-contributions/joystreamtelegrambot/package.json | 1 + community-contributions/joystreamtelegrambot/src/bot.ts | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/community-contributions/joystreamtelegrambot/package.json b/community-contributions/joystreamtelegrambot/package.json index 5e268081d..6776946cb 100644 --- a/community-contributions/joystreamtelegrambot/package.json +++ b/community-contributions/joystreamtelegrambot/package.json @@ -27,6 +27,7 @@ "discord.js": "^12.5.3", "moment": "^2.29.1", "node-telegram-bot-api": "^0.51.0", + "string-strip-html": "^8.3.0", "ws": "^7.4.1" }, "devDependencies": { diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index 2b04b864d..af050e269 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -8,6 +8,7 @@ import { proposalDelay, wsLocation, } from "../config"; +import { stripHtml } from "string-strip-html"; // types import { Block, Council, Options, Proposals } from "./types"; @@ -69,8 +70,10 @@ const sendTelegram = (msg: string) => { }; const sendDiscord = (msg: string, channel: any) => { if (!channel) return; + const stripped: string = stripHtml(msg).result; + if (!stripped.length) return; try { - channel.send(msg); + channel.send(stripped); } catch (e) { console.log(e); } From b6bc3030ca9483496ee2e3201b7c01e915328a20 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Fri, 23 Jul 2021 17:19:31 +0000 Subject: [PATCH 04/12] dicord: include link --- .../joystreamtelegrambot/src/bot.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index af050e269..0a527a3ee 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -70,7 +70,18 @@ const sendTelegram = (msg: string) => { }; const sendDiscord = (msg: string, channel: any) => { if (!channel) return; - const stripped: string = stripHtml(msg).result; + + const options = { + dumpLinkHrefsNearby: { + enabled: false, + putOnNewLine: false, + wrapHeads: "", + wrapTails: "", + }, + }; + + const stripped: string = stripHtml(msg, options).result; + if (!stripped.length) return; try { channel.send(stripped); From 9c7deb566fb15b76de73d1fab08a214b1f97fac3 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Fri, 23 Jul 2021 17:20:06 +0000 Subject: [PATCH 05/12] heartbeat: add token value --- community-contributions/joystreamtelegrambot/package.json | 1 + community-contributions/joystreamtelegrambot/src/bot.ts | 5 +++-- .../joystreamtelegrambot/src/lib/announcements.ts | 7 +++++-- .../joystreamtelegrambot/src/lib/getters.ts | 6 ++++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/package.json b/community-contributions/joystreamtelegrambot/package.json index 6776946cb..1ce3e4556 100644 --- a/community-contributions/joystreamtelegrambot/package.json +++ b/community-contributions/joystreamtelegrambot/package.json @@ -24,6 +24,7 @@ }, "dependencies": { "@joystream/types": "^0.16.1", + "axios": "^0.21.1", "discord.js": "^12.5.3", "moment": "^2.29.1", "node-telegram-bot-api": "^0.51.0", diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index 0a527a3ee..87b25fb5b 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -40,6 +40,7 @@ client.on("ready", async () => { discordChannels.council = await findDiscordChannel("council"); discordChannels.proposals = await findDiscordChannel("proposals-bot"); discordChannels.forum = await findDiscordChannel("forum-bot"); + discordChannels.tokenomics = await findDiscordChannel("tokenomics"); }); const findDiscordChannel = (name: string) => @@ -190,13 +191,13 @@ const main = async () => { // heartbeat if (timestamp > lastHeartbeat + heartbeat) { const time = passedTime(lastHeartbeat, timestamp); - blocks = announce.heartbeat( + blocks = await announce.heartbeat( api, blocks, time, proposals, sendMessage, - discordChannels.proposals + discordChannels.tokenomics ); lastHeartbeat = block.timestamp; } diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 5365003ac..6b56be5e9 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -17,6 +17,7 @@ import { memberHandle, memberHandleByAccount, proposalDetail, + fetchTokenValue, } from "./getters"; import moment from "moment"; @@ -238,14 +239,15 @@ export const proposals = async ( const getAverage = (array: number[]): number => array.reduce((a: number, b: number) => a + b, 0) / array.length; -export const heartbeat = ( +export const heartbeat = async ( api: Api, blocks: Block[], timePassed: string, proposals: Proposals, sendMessage: Send, channel: any -): [] => { +): Promise<[]> => { + const price = await fetchTokenValue(); const durations = blocks.map((b) => b.duration); const blocktime = getAverage(durations) / 1000; @@ -273,6 +275,7 @@ export const heartbeat = ( const msg = ` ${blocks.length} blocks produced in ${timePassed} Blocktime: ${blocktime.toFixed(3)}s + Price: ${price} Stake: ${avgStake.toFixed(1)} / ${avgIssued.toFixed()} M tJOY (${percent}%) Validators: ${avgVals.toFixed()} (${reward} tJOY/h) Nominators: ${getAverage(noms).toFixed()} diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index f2e975445..ba7a039b7 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/getters.ts @@ -1,4 +1,5 @@ import { formatProposalMessage } from "./announcements"; +import axios from "axios"; //types @@ -108,3 +109,8 @@ export const proposalDetail = async ( const createdAt: number = proposal.createdAt.toNumber(); 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} $` : `?`; +}; From 9af242aef2cb914f9e796a3c2a01a605c18609ec Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Fri, 23 Jul 2021 18:12:00 +0000 Subject: [PATCH 06/12] heartbeat: announce storage size --- .../joystreamtelegrambot/src/lib/announcements.ts | 6 +++++- .../joystreamtelegrambot/src/lib/getters.ts | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 6b56be5e9..04c81d75a 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -18,6 +18,7 @@ import { memberHandleByAccount, proposalDetail, fetchTokenValue, + fetchStorageSize, } from "./getters"; import moment from "moment"; @@ -248,6 +249,7 @@ export const heartbeat = async ( channel: any ): Promise<[]> => { const price = await fetchTokenValue(); + const storageSize = await fetchStorageSize(); const durations = blocks.map((b) => b.duration); const blocktime = getAverage(durations) / 1000; @@ -279,7 +281,9 @@ export const heartbeat = async ( Stake: ${avgStake.toFixed(1)} / ${avgIssued.toFixed()} M tJOY (${percent}%) Validators: ${avgVals.toFixed()} (${reward} tJOY/h) Nominators: ${getAverage(noms).toFixed()} - ${proposalString}`; + Volume: ${storageSize} + ${proposalString} + `; sendMessage(msg, channel); return []; diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index ba7a039b7..42013f7cd 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/getters.ts @@ -114,3 +114,13 @@ export const fetchTokenValue = async () => { const { data } = await axios.get("https://status.joystream.org/status"); return data ? `${Math.floor(+data.price * 100000000) / 100} $` : `?`; }; + +export const fetchStorageSize = async () => { + const dashboard = "https://analytics.dapplooker.com/api/public/dashboard"; + const asset = "c70b56bd-09a0-4472-a557-796afdc64d3b/card/155"; + + const { data } = await axios.get(`${dashboard}/${asset}`); + + const size = Math.round(data.data.rows[0][0]) + "GB"; + return size; +}; From 05ac025924a3ace5ae955fb0f27ce538bf1ca86d Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Sat, 24 Jul 2021 13:16:33 +0000 Subject: [PATCH 07/12] announce: show token value with currency --- .../joystreamtelegrambot/src/lib/announcements.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 04c81d75a..a754596d9 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -277,7 +277,7 @@ export const heartbeat = async ( const msg = ` ${blocks.length} blocks produced in ${timePassed} Blocktime: ${blocktime.toFixed(3)}s - Price: ${price} + Price: ${price} / 1 M tJOY Stake: ${avgStake.toFixed(1)} / ${avgIssued.toFixed()} M tJOY (${percent}%) Validators: ${avgVals.toFixed()} (${reward} tJOY/h) Nominators: ${getAverage(noms).toFixed()} From 3e8b6a83655763de0e17a2fe870e4a281b56904f Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Tue, 27 Jul 2021 15:23:59 +0000 Subject: [PATCH 08/12] fix double sending Note: composing messages took longer than a block for some notifications and they were sent multiple times. --- .../joystreamtelegrambot/src/bot.ts | 22 +++++++++---------- .../src/lib/announcements.ts | 6 ++--- .../joystreamtelegrambot/src/lib/getters.ts | 2 +- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index 87b25fb5b..eb832e550 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -121,6 +121,7 @@ const main = async () => { let stake = 0; let vals = 0; let noms = 0; + let announced: { [key: string]: boolean } = {}; const channels: number[] = [0, 0]; const posts: number[] = [0, 0]; @@ -191,7 +192,7 @@ const main = async () => { // heartbeat if (timestamp > lastHeartbeat + heartbeat) { const time = passedTime(lastHeartbeat, timestamp); - blocks = await announce.heartbeat( + announce.heartbeat( api, blocks, time, @@ -200,6 +201,7 @@ const main = async () => { discordChannels.tokenomics ); lastHeartbeat = block.timestamp; + blocks = []; } // announcements @@ -215,21 +217,23 @@ const main = async () => { if (opts.channel) { channels[1] = await get.currentChannelId(api); if (channels[1] > channels[0]) - channels[0] = await announce.channels( + announce.channels( api, channels, sendMessage, discordChannels.channels ); + channels[0] = channels[1]; } if (opts.proposals) { proposals.current = await get.proposalCount(api); + if ( - proposals.current > proposals.last || - (timestamp > lastProposalUpdate + 60000 * proposalDelay && - (proposals.active || proposals.executing)) + proposals.current > proposals.last && + !announced[proposals.current] ) { + announced[`proposal${proposals.current}`] = true; proposals = await announce.proposals( api, proposals, @@ -243,12 +247,8 @@ const main = async () => { if (opts.forum) { posts[1] = await get.currentPostId(api); - posts[0] = await announce.posts( - api, - posts, - sendMessage, - discordChannels.forum - ); + announce.posts(api, posts, sendMessage, discordChannels.forum); + posts[0] = posts[1]; } printStatus(opts, { block: id, chain, posts, proposals }); diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index a754596d9..0dcc64b09 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -40,7 +40,7 @@ export const channels = async ( channels: number[], sendMessage: Send, channel: any -): Promise => { +): Promise => { const [last, current] = channels; const messages: string[] = []; @@ -56,7 +56,6 @@ export const channels = async ( ); } sendMessage(messages.join("\r\n\r\n"), channel); - return current; }; // announce council change @@ -247,7 +246,7 @@ export const heartbeat = async ( proposals: Proposals, sendMessage: Send, channel: any -): Promise<[]> => { +): Promise => { const price = await fetchTokenValue(); const storageSize = await fetchStorageSize(); const durations = blocks.map((b) => b.duration); @@ -286,7 +285,6 @@ export const heartbeat = async ( `; sendMessage(msg, channel); - return []; }; export const formatProposalMessage = (data: string[]): string => { diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index 42013f7cd..6bca1a67a 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/getters.ts @@ -16,7 +16,7 @@ import { Proposal } from "@joystream/types/proposals"; // channel -export const currentChannelId = async (api: Api): Promise => -1 +export const currentChannelId = async (api: Api): Promise => -1; export const memberHandle = async (api: Api, id: MemberId): Promise => { const membership: Membership = await api.query.members.membershipById(id); From 253cf94fb6bb20373cf4adb3ef414cbba13c792f Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Sat, 7 Aug 2021 19:56:41 +0000 Subject: [PATCH 09/12] format discord messages --- .../joystreamtelegrambot/src/bot.ts | 25 +--- .../src/lib/announcements.ts | 120 ++++++++++++------ .../joystreamtelegrambot/src/lib/getters.ts | 2 +- .../joystreamtelegrambot/src/types/index.ts | 4 +- 4 files changed, 87 insertions(+), 64 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index eb832e550..fc4514f49 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -56,10 +56,10 @@ client.on("message", async (msg) => { let lastHeartbeat: number = moment().valueOf(); // send to telegram and discord -const sendMessage = (msg: string, channel: any) => { - if (msg === "") return; - sendDiscord(msg, channel); - sendTelegram(msg); +const sendMessage = (msg: { tg: string; discord: string }, channel: any) => { + if (msg.tg === "") return; + sendDiscord(msg.discord, channel); + sendTelegram(msg.tg); }; const sendTelegram = (msg: string) => { try { @@ -70,22 +70,9 @@ const sendTelegram = (msg: string) => { } }; const sendDiscord = (msg: string, channel: any) => { - if (!channel) return; - - const options = { - dumpLinkHrefsNearby: { - enabled: false, - putOnNewLine: false, - wrapHeads: "", - wrapTails: "", - }, - }; - - const stripped: string = stripHtml(msg, options).result; - - if (!stripped.length) return; + if (!channel || !msg.length) return; try { - channel.send(stripped); + channel.send(msg); } catch (e) { console.log(e); } diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 0dcc64b09..6dd88cdea 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -42,7 +42,7 @@ export const channels = async ( channel: any ): Promise => { const [last, current] = channels; - const messages: string[] = []; + const messages: string[][] = [[], []]; for (let id: number = +last + 1; id <= current; id++) { const channel: Channel = await query("title", () => @@ -51,11 +51,17 @@ export const channels = async ( const member: Member = { id: channel.owner.asMember, handle: "", url: "" }; member.handle = await memberHandle(api, member.id); member.url = `${domain}/#/members/${member.handle}`; - messages.push( + messages[0].push( `Channel ${id} by ${member.handle} (${member.id})` ); + messages[1].push( + `**Channel ${id}** by ${member.handle} (${member.id})\n${domain}/#//media/channels/${id}` + ); } - sendMessage(messages.join("\r\n\r\n"), channel); + sendMessage( + { tg: messages[0].join("\r\n\r\n"), discord: messages[1].join(`\n\n`) }, + channel + ); }; // announce council change @@ -71,7 +77,7 @@ export const council = async ( const stage: any = await api.query.councilElection.stage(); const stageObj = JSON.parse(JSON.stringify(stage)); let stageString = stageObj ? Object.keys(stageObj)[0] : ""; - let msg = ""; + let msg: string[] = ["", ""]; if (!stage || stage.toJSON() === null) { stageString = "elected"; @@ -91,19 +97,25 @@ export const council = async ( ); const members = handles.join(", "); - msg = `Council election ended: ${members} have been elected for council ${round}. Congratulations!\nNext election starts on ${endDate}.`; + msg[0] = `Council election ended: ${members} have been elected for council ${round}. Congratulations!\nNext election starts on ${endDate}.`; + msg[1] = `Council election ended: ${members} have been elected for council ${round}. Congratulations!\nNext election starts on ${endDate}.\n${domain}/#/council/members`; } } else { const remainingBlocks = stage.toJSON()[stageString] - currentBlock; const m = moment().add(remainingBlocks * 6, "second"); const endDate = formatTime(m, "DD-MM-YYYY HH:mm (UTC)"); - if (stageString === "Announcing") - msg = `Council election started. You can announce your application until ${endDate}`; - else if (stageString === "Voting") - msg = `Council election: Vote until ${endDate}`; - else if (stageString === "Revealing") - msg = `Council election: Reveal your votes until ${endDate}`; + const link = `${domain}/#/council/`; + if (stageString === "Announcing") { + msg[0] = `Council election started. You can announce your application until ${endDate}`; + msg[1] = `Council election started. You can **announce your application** until ${endDate} ${link}applicants`; + } else if (stageString === "Voting") { + msg[0] = `Council election: Vote until ${endDate}`; + msg[1] = `Council election: **Vote* until ${endDate} ${link}applicants`; + } else if (stageString === "Revealing") { + msg[0] = `Council election: Reveal your votes until ${endDate}`; + msg[1] = `Council election: **Reveal your votes** until ${endDate} ${link}votes`; + } } if ( @@ -111,7 +123,7 @@ export const council = async ( round !== council.round && stageString !== council.last ) - sendMessage(msg, channel); + sendMessage({ tg: msg[0], discord: msg[1] }, channel); return { round, last: stageString }; }; @@ -124,15 +136,22 @@ export const categories = async ( channel: any ): Promise => { if (category[0] === category[1]) return category[0]; - const messages: string[] = []; + const messages: string[][] = [[], []]; for (let id: number = +category[0] + 1; id <= category[1]; id++) { const cat: Category = await query("title", () => categoryById(api, id)); - const msg = `Category ${id}: ${cat.title}`; - messages.push(msg); + messages[0].push( + `Category ${id}: ${cat.title}` + ); + messages[1].push( + `Category ${id}: **${cat.title}** ${domain}/#/forum/categories/${id}` + ); } - sendMessage(messages.join("\r\n\r\n"), channel); + sendMessage( + { tg: messages[0].join("\r\n\r\n"), discord: messages[1].join(`\n\n`) }, + channel + ); return category[1]; }; @@ -145,7 +164,7 @@ export const posts = async ( ): Promise => { const [last, current] = posts; if (current === last) return last; - const messages: string[] = []; + const messages: string[][] = [[], []]; for (let id: number = +last + 1; id <= current; id++) { const post: Post = await query("current_text", () => @@ -167,19 +186,22 @@ export const posts = async ( const handle = await memberHandleByAccount(api, post.author_id.toJSON()); const s = { - author: `${handle}`, - thread: `${thread.title}`, - category: `${category.title}`, - content: `${post.current_text.substring(0, 150)} `, - link: `more`, + content: post.current_text.substring(0, 250), + link: `${domain}/#/forum/threads/${threadId}?replyIdx=${replyId}`, }; - messages.push( - `${s.category} ${s.author} posted in ${s.thread}:\n\r${s.content}${s.link}` + messages[0].push( + `${category.title} ${handle} posted in ${thread.title}:\n\r${s.content} more` + ); + messages[1].push( + `**[${category.title}]** ${handle} posted in **${thread.title}**:\n*${s.content}*\nMore: ${s.link}` ); } - sendMessage(messages.join("\r\n\r\n"), channel); + sendMessage( + { tg: messages[0].join("\r\n\r\n"), discord: messages[1].join(`\n\n`) }, + channel + ); return current; }; @@ -200,8 +222,10 @@ export const proposals = async ( const endTime = moment() .add(6 * (votingEndsAt - block), "second") .format("DD/MM/YYYY HH:mm"); - const msg = `Proposal ${id} created at block ${createdAt}.\r\n${message}\r\nYou can vote until ${endTime} UTC (block ${votingEndsAt}).`; - sendMessage(msg, channel); + const link = `${domain}/#/proposals/${id}`; + const tg = `Proposal ${id} created at block ${createdAt}.\r\n${message.tg}\r\nYou can vote until ${endTime} UTC (block ${votingEndsAt}).`; + const discord = `Proposal ${id} **created** at block ${createdAt}. ${message.discord}\nVote until ${endTime} UTC (block ${votingEndsAt}). ${link}`; + sendMessage({ tg, discord }, channel); active.push(id); } @@ -215,8 +239,10 @@ export const proposals = async ( label = executed ? "executed" : "finalized"; if (!executed) executing.push(id); } - const msg = `Proposal ${id} ${label} at block ${finalizedAt}.\r\n${message}`; - sendMessage(msg, channel); + const link = `${domain}/#/proposals/${id}`; + const tg = `Proposal ${id} ${label} at block ${finalizedAt}.\r\n${message.tg}`; + const discord = `Proposal ${id} **${label}** at block ${finalizedAt}.\n${message.discord}\n${link}`; + sendMessage({ tg, discord }, channel); active = active.filter((a) => a !== id); } } @@ -226,8 +252,10 @@ export const proposals = async ( const { finalizedAt, message, parameters } = proposal; const executesAt = +finalizedAt + parameters.gracePeriod.toNumber(); if (block < executesAt) continue; - const msg = `Proposal ${id} executed at block ${executesAt}.\r\n${message}`; - sendMessage(msg, channel); + const link = `${domain}/#/proposals/${id}`; + const tg = `Proposal ${id} executed at block ${executesAt}.\r\n${message.tg}`; + const discord = `Proposal ${id} **executed** at block ${executesAt}.\n${message.discord}\n${link}`; + sendMessage({ tg, discord }, channel); executing = executing.filter((e) => e !== id); } @@ -268,11 +296,16 @@ export const heartbeat = async ( const pending = proposals.active.length; const finalized = proposals.executing.length; const p = (n: number) => (n > 1 ? "proposals" : "proposal"); - let proposalString = pending - ? `${pending} pending ${p(pending)} ` - : ""; + let proposalString: string[] = pending + ? [ + `${pending} pending ${p(pending)} `, + `${pending} pending ${p(pending)} ${domain}/#/proposals`, + ] + : ["", ""]; if (finalized) - proposalString += `${finalized} ${p(finalized)} in grace period.`; + proposalString = proposalString.map( + (s) => (s += `${finalized} ${p(finalized)} in grace period.`) + ); const msg = ` ${blocks.length} blocks produced in ${timePassed} Blocktime: ${blocktime.toFixed(3)}s @@ -280,14 +313,17 @@ export const heartbeat = async ( Stake: ${avgStake.toFixed(1)} / ${avgIssued.toFixed()} M tJOY (${percent}%) Validators: ${avgVals.toFixed()} (${reward} tJOY/h) Nominators: ${getAverage(noms).toFixed()} - Volume: ${storageSize} - ${proposalString} - `; - - sendMessage(msg, channel); + Volume: ${storageSize}\n`; + const tg = msg + proposalString[0]; + const discord = msg + proposalString[1]; + sendMessage({ tg, discord }, channel); }; -export const formatProposalMessage = (data: string[]): string => { +export const formatProposalMessage = ( + data: string[] +): { tg: string; discord: string } => { const [id, title, type, stage, result, handle] = data; - return `Type: ${type}\r\nProposer: ${handle}\r\nTitle: ${title}\r\nStage: ${stage}\r\nResult: ${result}`; + const tg = `Type: ${type}\r\nProposer: ${handle}\r\nTitle: ${title}\r\nStage: ${stage}\r\nResult: ${result}`; + const discord = `**Type**: ${type}\n**Proposer**: ${handle}\n**Title**: ${title}\n**Stage**: ${stage}\n**Result*: ${result}\n${domain}/#/proposals/${id}`; + return { tg, discord }; }; diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index 6bca1a67a..78eb3bb3c 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/getters.ts @@ -105,7 +105,7 @@ export const proposalDetail = async ( const title: string = proposal.title.toString(); const type: string = await getProposalType(api, id); const args: string[] = [String(id), title, type, stage, result, author]; - const message: string = formatProposalMessage(args); + const message: { tg: string; discord: string } = formatProposalMessage(args); const createdAt: number = proposal.createdAt.toNumber(); return { createdAt, finalizedAt, parameters, message, stage, result, exec }; }; diff --git a/community-contributions/joystreamtelegrambot/src/types/index.ts b/community-contributions/joystreamtelegrambot/src/types/index.ts index 4b25b32bc..74b35e648 100644 --- a/community-contributions/joystreamtelegrambot/src/types/index.ts +++ b/community-contributions/joystreamtelegrambot/src/types/index.ts @@ -26,7 +26,7 @@ export interface Options { export interface ProposalDetail { createdAt: number; finalizedAt: number; - message: string; + message: { tg: string; discord: string }; parameters: ProposalParameters; stage: string; result: string; @@ -59,4 +59,4 @@ export interface Block { reward: number; } -export type Send = (msg: string, channel: any) => void; +export type Send = (msg: { tg: string; discord: string }, channel: any) => void; From 08b297863c0f9aa437d41a512c3432078e16670b Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Sun, 8 Aug 2021 20:26:20 +0000 Subject: [PATCH 10/12] improve msg format --- .../joystreamtelegrambot/src/lib/announcements.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 6dd88cdea..834cda1b6 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts @@ -223,8 +223,8 @@ export const proposals = async ( .add(6 * (votingEndsAt - block), "second") .format("DD/MM/YYYY HH:mm"); const link = `${domain}/#/proposals/${id}`; - const tg = `Proposal ${id} created at block ${createdAt}.\r\n${message.tg}\r\nYou can vote until ${endTime} UTC (block ${votingEndsAt}).`; - const discord = `Proposal ${id} **created** at block ${createdAt}. ${message.discord}\nVote until ${endTime} UTC (block ${votingEndsAt}). ${link}`; + const tg = `Proposal ${id} created at block ${createdAt}.\r\n${message.tg}\r\nYou can vote until block ${votingEndsAt} (${endTime} UTC).`; + const discord = `Proposal ${id} **created** at block ${createdAt}. ${message.discord}\nVote until block ${votingEndsAt} (${endTime} UTC): ${link}`; sendMessage({ tg, discord }, channel); active.push(id); } @@ -324,6 +324,6 @@ export const formatProposalMessage = ( ): { tg: string; discord: string } => { const [id, title, type, stage, result, handle] = data; const tg = `Type: ${type}\r\nProposer: ${handle}\r\nTitle: ${title}\r\nStage: ${stage}\r\nResult: ${result}`; - const discord = `**Type**: ${type}\n**Proposer**: ${handle}\n**Title**: ${title}\n**Stage**: ${stage}\n**Result*: ${result}\n${domain}/#/proposals/${id}`; + const discord = `**Type**: ${type}\n**Proposer**: ${handle}\n**Title**: ${title}\n**Stage**: ${stage}\n**Result**: ${result}`; return { tg, discord }; }; From aa5a8f4964152e4fc93952446573ee421d655b76 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Thu, 12 Aug 2021 18:10:44 +0000 Subject: [PATCH 11/12] string improvements --- .../joystreamtelegrambot/src/bot.ts | 33 ++++++------------- .../src/lib/announcements.ts | 9 ++--- .../joystreamtelegrambot/src/lib/getters.ts | 23 +++++++++---- .../joystreamtelegrambot/src/lib/util.ts | 5 --- 4 files changed, 31 insertions(+), 39 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index fc4514f49..b0f5b6fa7 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/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(); }); diff --git a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts b/community-contributions/joystreamtelegrambot/src/lib/announcements.ts index 834cda1b6..c40027f7c 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/announcements.ts +++ b/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 = `Proposal ${id} created at block ${createdAt}.\r\n${message.tg}\r\nYou can vote 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 = `Proposal ${id} ${label} 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 = `Proposal ${id} executed 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 ? [ `${pending} pending ${p(pending)} `, - `${pending} pending ${p(pending)} ${domain}/#/proposals`, + `${pending} active ${p(pending)} ${domain}/#/proposals`, ] : ["", ""]; if (finalized) diff --git a/community-contributions/joystreamtelegrambot/src/lib/getters.ts b/community-contributions/joystreamtelegrambot/src/lib/getters.ts index 78eb3bb3c..d16b71a1b 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/getters.ts +++ b/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 => -1; +export const timestamp = async (api: Api) => + (await api.query.timestamp.now()).toNumber(); export const memberHandle = async (api: Api, id: MemberId): Promise => { 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 => + 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; }; diff --git a/community-contributions/joystreamtelegrambot/src/lib/util.ts b/community-contributions/joystreamtelegrambot/src/lib/util.ts index 06bfb4fc9..68f99f430 100644 --- a/community-contributions/joystreamtelegrambot/src/lib/util.ts +++ b/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(); -}; From f4b8071df2d6c09fd854e2ade3bc7e25222b0771 Mon Sep 17 00:00:00 2001 From: Joystream Stats Date: Thu, 19 Aug 2021 17:18:36 +0000 Subject: [PATCH 12/12] drop string-strip-html --- community-contributions/joystreamtelegrambot/package.json | 1 - community-contributions/joystreamtelegrambot/src/bot.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/community-contributions/joystreamtelegrambot/package.json b/community-contributions/joystreamtelegrambot/package.json index 1ce3e4556..0ab8b549a 100644 --- a/community-contributions/joystreamtelegrambot/package.json +++ b/community-contributions/joystreamtelegrambot/package.json @@ -28,7 +28,6 @@ "discord.js": "^12.5.3", "moment": "^2.29.1", "node-telegram-bot-api": "^0.51.0", - "string-strip-html": "^8.3.0", "ws": "^7.4.1" }, "devDependencies": { diff --git a/community-contributions/joystreamtelegrambot/src/bot.ts b/community-contributions/joystreamtelegrambot/src/bot.ts index b0f5b6fa7..dd5c6fcf5 100644 --- a/community-contributions/joystreamtelegrambot/src/bot.ts +++ b/community-contributions/joystreamtelegrambot/src/bot.ts @@ -8,7 +8,6 @@ import { proposalDelay, wsLocation, } from "../config"; -import { stripHtml } from "string-strip-html"; // types import { Block, Council, Options, Proposals } from "./types";