Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

add create subscription #4

Merged
merged 28 commits into from
Aug 4, 2021
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
e533157
add create subscription
fanamoner Jul 10, 2021
c44cbfb
add price model, change subscription model
fanamoner Jul 19, 2021
60b3011
Add classes for SubscriptionModel
fanamoner Jul 21, 2021
a2f74c9
Remove ctx usage in getOrCreateSubscription
fanamoner Jul 21, 2021
5d39f8b
Delete Price model
fanamoner Jul 21, 2021
ef65ec5
Refactor sendStart function
fanamoner Jul 22, 2021
f3c9150
Change return value of getOrCreateSubscription function
fanamoner Jul 22, 2021
8a44935
refactor getOrCreateSubscription function
fanamoner Jul 22, 2021
e5dbe0f
Set global options for every mongoDB model
fanamoner Jul 22, 2021
8d028e6
Add web3 helper
fanamoner Jul 22, 2021
48b3517
Add information about Web3 to .env.sample and README
fanamoner Jul 22, 2021
86f1d44
Make price property optional
fanamoner Jul 23, 2021
4da1370
Refactor sendStart function
fanamoner Jul 23, 2021
951112a
Refactor subscription model structure
fanamoner Jul 23, 2021
63eb0c6
Add subscriptionPrice variable for locales
fanamoner Jul 24, 2021
d219d47
Refactor database structure
fanamoner Jul 24, 2021
64bf92c
Delete setGlobalOptions
fanamoner Jul 25, 2021
698034e
Change sendStart function
fanamoner Jul 25, 2021
448c8e5
Refactor database structure
fanamoner Jul 30, 2021
04fa421
Add help message in sendStart function
fanamoner Jul 31, 2021
9a267ad
Remove union type in chatId property
fanamoner Jul 31, 2021
fb34b1d
Add typegoose helper
fanamoner Jul 31, 2021
9d9fbf2
Create indexes for subscription model
fanamoner Aug 1, 2021
0b387df
Add price check for subscription message
fanamoner Aug 1, 2021
875581c
Refactor getOrCreateSubscription function
fanamoner Aug 1, 2021
64c2abe
Refactor sendStart function and typegoose options
fanamoner Aug 3, 2021
091bb41
Refactor typegooseOptions.ts
fanamoner Aug 4, 2021
be11658
Refacor sendStart function
fanamoner Aug 4, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
TOKEN=123
MONGO=mongodb://localhost:27017/tlgcoin
MONGO=mongodb://localhost:27017/tlgcoin
WEB3_PROVIDER=http://localhost:27017
backmeupplz marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
backmeupplz marked this conversation as resolved.
Show resolved Hide resolved
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ And you should be good to go! Feel free to fork and submit pull requests. Thanks

- `TOKEN` — Telegram bot token
- `MONGO`— URL of the mongo database
- `WEB3_PROVIDER` - Your local/remote Ethereum node

Also, please, consider looking at `.env.sample`.

Expand Down
1 change: 1 addition & 0 deletions locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ language: Please, select the language.
language_selected: <b>Bot</b> now speaks English.
notifications_on: Notifications enabled
notifications_off: Notifications disabled
subscription_message: In order to subscribe to this group, you need to transfer 1 ETH to ${subscriptionAddress}.
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions locales/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ start_group_admin: Администратор группы подтвержде
start_group_not_admin: Простите, эта ссылка существует только для администраторов сообществ.
notifications_on: Уведомления включены
notifications_off: Уведомления отключены
subscription_message: Чтобы подписаться на этоу группу, вам нужно перевести 1 ETH по адресу ${subscriptionAddress}.
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"mongoose": "5.10.18",
"telegraf": "^4.3.0",
"telegraf-i18n": "^6.6.0",
"typescript": "^4.3.2"
"typescript": "^4.3.2",
"web3": "^1.4.0"
},
"_moduleAliases": {
"@": "dist"
Expand Down
4 changes: 4 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { attachChat } from '@/middlewares/attachChat'
import { handleMyChatMember } from '@/handlers/handleMyChatMember'
import { toggleNotifications } from '@/handlers/toggleNotifications'
import { stopIfPrivate } from '@/middlewares/stopIfPrivate'
import { runMongo } from '@/models/index'

// Middlewares
bot.use(ignoreOldMessageUpdates)
Expand All @@ -32,6 +33,9 @@ bot.on('my_chat_member', stopIfPrivate, handleMyChatMember)
// Errors
bot.catch(console.error)
// Start bot
runMongo().then(() => {
console.log('Mongo connected')
})
bot.launch().then(() => {
console.info(`Bot ${bot.botInfo.username} is up and running`)
})
19 changes: 17 additions & 2 deletions src/handlers/handleStart.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Context } from 'telegraf'
import { MessageAfterLanguage, sendLanguage } from '@/handlers/language'
import { getOrCreateSubscription } from '@/models/Subscription'

export function handleStart(ctx: Context) {
return sendStart(ctx)
Expand All @@ -20,11 +21,25 @@ export async function sendStart(ctx: Context) {

fanamoner marked this conversation as resolved.
Show resolved Hide resolved
const allowedStatuses = ['administrator', 'creator']
if (allowedStatuses.includes(chatMemberInfo.status)) {
return ctx.reply(ctx.i18n.t('start_group_admin'))
ctx.reply(ctx.i18n.t('start_group_admin'))
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
const subscription = await getOrCreateSubscription(
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
ctx.from.id,
ctx.chat.id
)
ctx.reply(
ctx.i18n.t('subscription_message', {
subscriptionAddress: subscription.accounts.eth.address,
})
)
} else {
return ctx.reply(ctx.i18n.t('start_group_not_admin'))
}
}

return ctx.replyWithHTML(ctx.i18n.t('help'))
const subscription = await getOrCreateSubscription(ctx.from.id, ctx.chat.id)
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
ctx.reply(
ctx.i18n.t('subscription_message', {
subscriptionAddress: subscription.accounts.eth.address,
})
)
}
3 changes: 3 additions & 0 deletions src/helpers/web3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import Web3 from 'web3'

export const web3 = new Web3(Web3.givenProvider || process.env.WEB3_PROVIDER)
4 changes: 1 addition & 3 deletions src/models/Chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ export class Chat {
}

// Get Chat model
const ChatModel = getModelForClass(Chat, {
schemaOptions: { timestamps: true },
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
})
const ChatModel = getModelForClass(Chat)

// Get or create chat
export async function findChat(id: number) {
Expand Down
56 changes: 56 additions & 0 deletions src/models/Subscription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {
prop,
getModelForClass,
Severity,
setGlobalOptions,
} from '@typegoose/typegoose'
import { web3 } from '@/helpers/web3'

interface Accounts {
eth: {
address: string
privateKey: string
}
}

interface Prices {
monthly: { eth: number }
}

setGlobalOptions({
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
schemaOptions: { timestamps: true },
options: { allowMixed: Severity.ALLOW },
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
})

export class Subscription {
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
@prop({ required: true })
userId: number
@prop({ required: true })
chatId: number
@prop({ required: true, unique: true })
accounts: Accounts
@prop()
prices?: Prices
}

export const SubscriptionModel = getModelForClass(Subscription)

export async function getOrCreateSubscription(userId: number, chatId: number) {
let subscription = await SubscriptionModel.findOne({
chatId,
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
})

if (subscription) {
return subscription
}

const ethAccount = web3.eth.accounts.create()

subscription = await SubscriptionModel.create({
userId,
chatId,
accounts: { eth: ethAccount },
})

return subscription
}
15 changes: 9 additions & 6 deletions src/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import * as mongoose from 'mongoose'
import mongoose from 'mongoose'

mongoose.connect(process.env.MONGO, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
mongoose.set('useCreateIndex', true)
export function runMongo(mongoUrl = process.env.MONGO) {
return mongoose.connect(mongoUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: true,
})
}

export * from './Chat'
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
"@/*": ["*"]
},
"emitDecoratorMetadata": true,
"experimentalDecorators": true
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
fanamoner marked this conversation as resolved.
Show resolved Hide resolved
"esModuleInterop": true
},
"include": ["src/**/*"]
}
Loading