Skip to content

Commit

Permalink
chore: more customization (closes #125)
Browse files Browse the repository at this point in the history
  • Loading branch information
egorprnn committed Oct 9, 2021
1 parent e4f6ea0 commit ef79d26
Show file tree
Hide file tree
Showing 14 changed files with 109 additions and 57 deletions.
45 changes: 33 additions & 12 deletions CONFIG_FIELDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[Заполненный пример config.json](https://github.com/MrZillaGold/VK2Discord/blob/master/config_example.json)


**VK**
### VK

| Поле | Пример заполнения | Описание |
| ----------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
Expand All @@ -18,14 +18,35 @@
| `donut` | `false` | Публиковать записи доступные по подписке [VKDonut](https://vk.com/blog/vk-donut). |
| `interval` | `30` | Интервал получения новых постов из ВКонтакте в секундах. Используется для ключа-доступа пользователя. |

**Discord**

| Поле | Пример заполнения | Описание |
| -------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `webhook_urls` | `["https://discordapp.com/api/webhooks/1", "https://discordapp.com/api/webhooks/2"]` | WebHook-ссылки, можно использовать несколько ссылок на разные каналы Discord. |
| `color` | `"#aabbcc"` | Цвет рамки сообщения Discord в формате [HEX](https://www.color-hex.com/). |
| `username` | `"VK2Discord"` | Имя для Webhook, показывается в качестве имени бота. (Строку можно оставить пустой, если не хотите менять Webhook имя) |
| `avatar_url` | `"https://sun9-29.userapi.com/rmoNl3t2KfRZlNpFbAwSEzeDwML-xczsHU6y1A/HApWIpxjkT4.jpg"` | Ссылка на аватар Webhook, показывается в качестве аватарки бота. (Строку можно оставить пустой, если не хотите менять Webhook аватар) |
| `content` | `"Новая запись! @everyone"` | Сообщение которое добавляется перед отправкой, можно использовать для упоминаний. |
| `author` | `false` | Указывать автора записи ВКонтакте (если имеется) в сообщении Discord. |
| `copyright` | `true` | Указывать источник записи ВКонтакте и подпись автора (если имеется) в сообщении Discord. |
### Discord

| Поле | Пример заполнения | Описание |
| ----------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `webhook_urls` | `["https://discordapp.com/api/webhooks/1", "https://discordapp.com/api/webhooks/2"]` | WebHook-ссылки, можно использовать несколько ссылок на разные каналы Discord. |
| `color` | `"#aabbcc"` | Цвет рамки сообщения Discord в формате [HEX](https://www.color-hex.com/). |
| `username` | `"VK2Discord"` | Имя для Webhook, показывается в качестве имени бота. (Строку можно оставить пустой, если не хотите менять Webhook имя) |
| `avatar_url` | `"https://sun9-29.userapi.com/rmoNl3t2KfRZlNpFbAwSEzeDwML-xczsHU6y1A/HApWIpxjkT4.jpg"` | Ссылка на аватар Webhook, используется в качестве аватарки бота. (Строку можно оставить пустой, если не хотите менять Webhook аватар) |
| `content` | `"Новая запись! @everyone"` | Сообщение которое добавляется перед отправкой, можно использовать для упоминаний. |
| `author` | `false` | Указывать автора записи ВКонтакте (если имеется) в сообщении Discord. |
| `copyright` | `true` | Указывать источник записи ВКонтакте и подпись автора (если имеется) в сообщении Discord. |
| `date` | `true` | Добавлять дату публикации записи ВКонтакте в сообщении Discord. |
| `exclude_content` | `["photo", "text", "video"]` | Массив с типами контента для исключения из сообщения Discord. [Доступные значения](#доступный-контент-для-исключения). |

#### Доступный контент для исключения

| Тип | Описание |
| --------------------- | ------------------------ |
| `audio` | Аудиозапись |
| `doc` | Документ |
| `link` | Сниппет-ссылка |
| `photo` | Фотография |
| `poll` | Опрос |
| `video` | Видео |
| `album` | Альбом |
| `market` | Товар |
| `market_album` | Подборка товаров |
| `textlive` | Тестовая трансляция |
| `text` | Текст записи |
| `attachments` | Вложения записи |
| `repost_text` | Текст репоста |
| `repost_attachments` | Вложения репоста |
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/mrzillagold/vk2discord?label=%D0%97%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B8%20Docker&logo=docker">
</a>
<a href="https://wakatime.com/badge/github/MrZillaGold/VK2Discord">
<img alt="Docker Pulls" src="https://wakatime.com/badge/github/MrZillaGold/VK2Discord.svg">
<img alt="wakatime" src="https://wakatime.com/badge/github/MrZillaGold/VK2Discord.svg">
</a>
<a href="https://github.com/MrZillaGold/VK2Discord/actions/workflows/ci.yml">
<img alt="Build Status" src="https://github.com/MrZillaGold/VK2Discord/actions/workflows/ci.yml/badge.svg">
Expand Down
6 changes: 4 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
"content": "",
"color": "#aabbcc",
"author": true,
"copyright": true
"copyright": true,
"date": true,
"exclude_content": []
}
}
],
"version_dont_modify_me": 4
"version_dont_modify_me": 5
}
6 changes: 4 additions & 2 deletions config_example.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"content": "@everyone",
"color": "#aabbcc",
"author": true,
"copyright": false
"copyright": false,
"date": false
}
},
{
Expand All @@ -45,7 +46,8 @@
"content": "",
"color": "#ffbbff",
"author": true,
"copyright": true
"copyright": true,
"date": true
}
}
],
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "vk2discord",
"version": "2.1.8",
"LATEST_CONFIG_VERSION": 4,
"version": "3.0.0",
"LATEST_CONFIG_VERSION": 5,
"description": "Автоматическая публикация записей из группы или профиля ВКонтакте в канал Discord.",
"main": "./build/index.js",
"type": "module",
Expand Down
4 changes: 3 additions & 1 deletion scripts/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ function createConfig() {
content: '',
color: '#aabbcc',
author: true,
copyright: true
copyright: true,
date: true,
exclude_content: []
}
}
],
Expand Down
3 changes: 2 additions & 1 deletion scripts/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const { clusters, version_dont_modify_me } = config;
const changes = new Map([
[2, [{}, { author: true, copyright: true }]],
[3, [{}, { content: '', username: '', avatar_url: '' }]],
[4, [{ donut: false, ads: false, words_blacklist: [] }, {}]]
[4, [{ donut: false, ads: false, words_blacklist: [] }, {}]],
[5, [{}, { date: true, exclude_content: [] }]]
]);

if (!clusters || !version_dont_modify_me) {
Expand Down
11 changes: 10 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HexColorString } from 'discord.js';

import { Handler, Storage, VK } from './modules';
import { AttachmentTypeUnion, Handler, Storage, VK } from './modules';

// @ts-ignore
import config from '../config.json';
Expand All @@ -22,6 +22,13 @@ export interface IVKParams {
interval: number;
}

export enum Exclude {
TEXT = 'text',
ATTACHMENTS = 'attachments',
REPOST_TEXT = 'repost_text',
REPOST_ATTACHMENTS = 'repost_attachments'
}

export interface IDiscordParams {
webhook_urls: string[];
username: string;
Expand All @@ -30,6 +37,8 @@ export interface IDiscordParams {
color: HexColorString;
author: boolean;
copyright: boolean;
date: boolean;
exclude_content: (AttachmentTypeUnion | Exclude)[];
}

export interface ICluster {
Expand Down
16 changes: 11 additions & 5 deletions src/modules/Attachments.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { MessageEmbed, MessageAttachment } from 'discord.js';
import { AttachmentType, ISharedAttachmentPayload, AttachmentTypeString } from 'vk-io';

import { VK, Message } from './';
import { Message } from './';
import { ICluster } from '../';

import { generateRandomString, LINK_PREFIX } from '../utils';

type AttachmentTypeUnion = AttachmentTypeString | 'textlive';
export type AttachmentTypeUnion = AttachmentTypeString | 'textlive';

export type Attachment = {
type: AttachmentTypeUnion;
Expand All @@ -17,13 +18,14 @@ const { AUDIO, DOCUMENT, LINK, PHOTO, POLL, VIDEO, ALBUM, MARKET, MARKET_ALBUM }

export class Attachments {

VK: VK;
private cluster: ICluster;

constructor(VK: VK) {
this.VK = VK;
constructor(cluster: Attachments['cluster']) {
this.cluster = cluster;
}

parse(attachments: Attachment[], embeds: Message['embeds'], files: Message['files']): string[] {
const { discord: { exclude_content } } = this.cluster;
const [embed] = embeds;

const attachmentFields: string[] = [];
Expand All @@ -39,6 +41,10 @@ export class Attachments {
.reduce<string[]>((parsedAttachments, {
type, photo, video, link, doc, audio, poll, album, textlive, market
}) => {
if (exclude_content.includes(type)) {
return parsedAttachments;
}

switch (type) {
case PHOTO: {
const { sizes } = photo;
Expand Down
12 changes: 8 additions & 4 deletions src/modules/Handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class Handler {
}

private startInterval(): void {
const { index, vk: { interval, group_id, filter }, discord: { author, copyright } } = this.cluster;
const { index, vk: { interval, group_id, filter }, discord: { author, copyright, date } } = this.cluster;

console.log(`[VK2Discord] Кластер #${index} будет проверять новые записи с интервалом в ${interval} секунд.`);

Expand Down Expand Up @@ -112,7 +112,9 @@ export class Handler {

const [embed] = sender.embeds;

embed.setTimestamp(payload.date as number * 1000);
if (date) {
embed.setTimestamp(payload.date as number * 1_000);
}

if (author) {
const postAuthor = getPostAuthor(payload as IWallPostContextPayload, profiles, groups);
Expand Down Expand Up @@ -141,7 +143,7 @@ export class Handler {
}

private startPolling(): void {
const { index, discord: { author, copyright } } = this.cluster;
const { index, discord: { author, copyright, date } } = this.cluster;

this.VK.updates.on('wall_post_new', async (context) => {
const payload = context['payload'];
Expand All @@ -151,7 +153,9 @@ export class Handler {

const [embed] = sender.embeds;

embed.setTimestamp(payload.date as number * 1000);
if (date) {
embed.setTimestamp(payload.date as number * 1_000);
}

if (author) {
const postAuthor = await getById(this.VK.api, payload.from_id as number);
Expand Down
42 changes: 19 additions & 23 deletions src/modules/Message.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { MessageAttachment, MessageEmbed } from 'discord.js';
import { IWallPostContextPayload } from 'vk-io';

import { Markdown, Attachments, Attachment } from './';
import { Attachment, Attachments, Markdown } from './';

import { ICluster } from '../';
import { Exclude, ICluster } from '../';

export enum PostType {
POST = 'post',
Expand Down Expand Up @@ -36,48 +36,44 @@ export abstract class Message {
}

protected async parsePost(): Promise<void> {
const { cluster: { VK }, payload: { text, attachments, copy_history } } = this;
const { cluster, payload: { text, attachments, copy_history } } = this;
const { VK, discord: { exclude_content } } = cluster;

if (text) {
this.post += `${
await new Markdown(VK)
.fix(text)
}\n`;
const attachmentsParser = new Attachments(cluster);
const markdown = new Markdown(VK);

if (text && !exclude_content.includes(Exclude.TEXT)) {
this.post += `${await markdown.fix(text)}\n`;
}

if (attachments) {
const parsedAttachments = new Attachments(VK)
.parse(attachments as Attachment[], this.embeds, this.files);
if (attachments && !exclude_content.includes(Exclude.ATTACHMENTS)) {
const parsedAttachments = attachmentsParser.parse(attachments as Attachment[], this.embeds, this.files);

this.attachAttachments(parsedAttachments, PostType.POST);
this.attach(parsedAttachments, PostType.POST);
}

const repost = copy_history ? copy_history[0] : null;

if (repost) {
if (repost && !exclude_content.includes(Exclude.REPOST_TEXT) && !exclude_content.includes(Exclude.REPOST_ATTACHMENTS)) {
const { text, from_id, id, attachments } = repost;

this.repost += `\n>>> [**Репост записи**](https://vk.com/wall${from_id}_${id})`;

if (text) {
this.repost += `\n\n${
await new Markdown(VK)
.fix(text)
}`;
if (text && !exclude_content.includes(Exclude.REPOST_TEXT)) {
this.repost += `\n\n${await markdown.fix(text)}`;
}

if (attachments) {
const parsedAttachments = new Attachments(VK)
.parse(attachments as Attachment[], this.embeds, this.files);
if (attachments && !exclude_content.includes(Exclude.REPOST_ATTACHMENTS)) {
const parsedAttachments = attachmentsParser.parse(attachments as Attachment[], this.embeds, this.files);

this.attachAttachments(parsedAttachments, PostType.REPOST);
this.attach(parsedAttachments, PostType.REPOST);
}
}

this.sliceMessage();
}

private attachAttachments(attachmentFields: string[], type: PostType): void {
private attach(attachmentFields: string[], type: PostType): void {
const { embeds: [embed] } = this;

switch (type) {
Expand Down
8 changes: 8 additions & 0 deletions src/modules/Sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ export class Sender extends Message {

await this.pushDate();

if (
!embed.description &&
!embed.fields.length &&
!embed.image
) {
return;
}

const results = await Promise.allSettled(
webhook_urls.map((url) => (
new WebhookClient({
Expand Down
3 changes: 2 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ const cluster = {
content: '',
color: '#ffbbff',
author: true,
copyright: true
copyright: true,
exclude_content: []
}
};

Expand Down

0 comments on commit ef79d26

Please sign in to comment.