Ejemplo n.º 1
0
    def __init__(self):

        self.token = token
        self.maska = maska
        self.viz_reg_bot = viz_reg["account"]
        self.viz_reg_wif = viz_reg["wif"]

        # Подключаем фразы бота
        import msg as bot_msg
        self.bot_msg = bot_msg

        self.tg = Api(self.token, report=True, PROXY=False)
        self.prepare_commands()

        self.viz = VizApi()

        self.bot_menu = Menu(menu.menu, self.commands, self.tg)
Ejemplo n.º 2
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_database_info()

pprint(tx)
input()
Ejemplo n.º 3
0
from bitshares import BitShares
from bitshares.instance import set_shared_bitshares_instance

# класс с расчетом цен на бирже BitShares
from btsParser.Parser import Parser
# класс для работы с VIZ (от Протея)
from tvizbase.api import Api

with open(os.path.dirname(__file__) + '/settings.json', 'r') as sett_file:
    settings = json.load(sett_file)
decimal.getcontext().rounding = 'ROUND_HALF_UP'
# подключение к ноде node в сети Bitshares
BTS = BitShares(node=settings['bitshares_node'])
set_shared_bitshares_instance(BTS)
# подключение к сети VIZ
viz = Api()
# инициализация класса
parser = Parser(settings)
# получение данных о глубине стаканов
parser.get_market_depth()
# получение данных об истории сделок
#parser.get_history_depth()
# публикация данных в блокчейне VIZ
viz.custom(
    'vizplus_bitshares_info',  # ID custom'а 
    [
        'vizplus_bitshares_info',  # название типа данных, может отличаться от ID
        {
            'time_utc':
            str(datetime.utcnow()),
            'average_bid_price':
Ejemplo n.º 4
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_active_witnesses()

pprint(tx)
input()
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

account = 'ksantoprotein'
wif = '5...'  #regular
json_metadata = {"profile": {}, "name": 'Протей'}

tx = b4.get_accounts([account])[0]
print(tx["json_metadata"])

input('ready?')

tx = b4.account_metadata(account, json_metadata, wif)
pprint(tx)

input()
Ejemplo n.º 6
0
class Tip23(Viz):
    def __init__(self):

        self.token = token
        self.maska = maska
        self.viz_reg_bot = viz_reg["account"]
        self.viz_reg_wif = viz_reg["wif"]

        # Подключаем фразы бота
        import msg as bot_msg
        self.bot_msg = bot_msg

        self.tg = Api(self.token, report=True, PROXY=False)
        self.prepare_commands()

        self.viz = VizApi()

        self.bot_menu = Menu(menu.menu, self.commands, self.tg)

    ##### ##### TG COMMANDS ##### #####

    def prepare_commands(self):

        self.tg.commands["private_text"] = self.private_text
        self.tg.commands["private_entities"] = self.private_entities
        self.tg.commands["chat_text"] = self.chat_text
        self.tg.commands["chat_entities"] = self.chat_entities
        self.tg.commands["chat_reply"] = self.chat_reply

        self.commands = {
            "help:Intro": self.help_intro,
            "help:Reg": self.help_reg,
            "vizsign": self.vizsign,
            "vizlogin": self.vizlogin,
            "vizwallet": self.vizwallet,
            "viz:Info": self.vizinfo,
            "vizinfo:ClaimNow": self.vizclaimnow,
            "vizreg": self.vizreg,
            "vizregYN:Yes": self.vizregyes,
            "vizdelYN:Yes": self.vizdelyes,
            "language:Russian": self.language,
            "language:English": self.language,
            "report:On": self.report,
            "report:Off": self.report,
        }

    ##### ##### CHAT ##### #####

    def private_text(self, message):
        self.bot_menu.resolve(message)

    def private_entities(self, message):
        self.bot_menu.resolve(message)
        pass

    def chat_text(self, message):
        #print(message["chat"]["id"], message["text"])
        #tg.send_message(message["chat"]["id"], 'get text')
        pass

    def chat_entities(self, message):

        user_id, chat_id, lng = self.get_params_chat(message)
        cmd = message["text"]

        cmd_all = ['/viz+', '/viz-']
        if (user_id in self.bot_menu.users_tg) and (cmd in cmd_all):
            db = self.bot_menu.users_tg[user_id]
            print(self.maska, 'CMD', chat_id, user_id, cmd)

            if cmd in ['/viz+', '/viz-']:
                target_account, target_chat, asset = 'vizaccount', 'vizchat', 'VIZ'

            if cmd in ['/viz+']:
                initiator = db.get(target_account, None)
                if initiator:
                    account, wif = initiator.split(':')
                    db.setdefault(target_chat, [])
                    if chat_id not in db[target_chat]:
                        if cmd == '/viz+':
                            tx = self.viz.get_accounts([account])[0]
                        try:
                            msg = ' '.join([' +' + str(int(tx["TIP"])), asset])
                        except:
                            msg = ' error data'

                        db[target_chat].append(chat_id)
                        self.tg.send_message(chat_id,
                                             self.bot_msg.InvestorBecome[lng] +
                                             msg,
                                             delete=True)
                        self.bot_menu.save()
                    else:
                        self.tg.send_message(chat_id,
                                             self.bot_msg.InvestorAlready[lng],
                                             delete=True)
                else:
                    self.tg.send_message(chat_id,
                                         self.bot_msg.MustConnectAccount[lng],
                                         delete=True)

            if cmd in ['/viz-']:
                chat_list = db.get(target_chat, [])
                if chat_id in chat_list:
                    db[target_chat].remove(chat_id)
                    self.tg.send_message(chat_id,
                                         self.bot_msg.InvestorWithdraw[lng] +
                                         asset,
                                         delete=True)
                    self.bot_menu.save()

    def chat_reply(self, message):
        user_id, chat_id, lng = self.get_params_chat(message)

        text = message["text"]
        user_name = '@' + str(message["from"].get("username", ''))
        message_id = str(message["message_id"])

        title = str(message["chat"]["title"])

        reply_id = str(message["reply_to_message"]["from"]["id"])
        reply_username = '******' + str(message["reply_to_message"]["from"].get(
            "username", ''))
        reply_text = str(message["reply_to_message"].get("text", ''))
        is_bot = str(message["reply_to_message"]["from"]["is_bot"])

        k_like, amount, target_main = text.count('+', 0, 5), 0, None

        if 'viz' == text[:3].lower():
            target_main = 'viz'
            try:
                amount = int(text.split()[0].lower().replace('viz', ''))
            except:
                amount = 1

        flag_for_del = True if k_like > 0 and len(text) <= 5 else False
        if flag_for_del:
            payload = [chat_id, message_id, self.tg.DEL_DELAY]
            self.tg.delete_message(payload)

        #if (k_like > 0) and (user_id != reply_id) and (str(is_bot) == 'False'):				# Если есть хоть один +, не самоап и не бот
        if (k_like > 0 or amount > 0) and (
                str(is_bot) == 'False'
        ):  # TEST for TEST Если есть хоть один +, самоап и не бот
            print(self.maska, user_id, reply_id, k_like, amount)
            if user_id in self.bot_menu.users_tg and reply_id in self.bot_menu.users_tg:  # Если юзеры в базе

                flag = False  # Отслеживаем в целом инвестора
                reports = []

                target_list = [target_main] if target_main else ['viz']
                for target in target_list:

                    state_acc, target_chat, wallet_acc = target + 'account', target + 'chat', target + 'wallet'

                    chat_list = self.bot_menu.users_tg[user_id].get(
                        target_chat, [])
                    if chat_id in chat_list:

                        flag = True

                        asset_account = self.bot_menu.users_tg[user_id].get(
                            state_acc, None)
                        asset_account_for_donate = self.bot_menu.users_tg[
                            reply_id].get(wallet_acc, None)
                        if asset_account and asset_account_for_donate:  # Если оба в базе
                            account, wif = asset_account.split(':')
                            account_for_donate = asset_account_for_donate

                            report = None
                            lines, comment = text.split(), ''
                            if len(lines) >= 2: comment = ' '.join(lines[1:])

                            if 'viz' == target:
                                report = self.viz_donate(account,
                                                         k_like,
                                                         title,
                                                         reply_text,
                                                         account_for_donate,
                                                         wif,
                                                         amount=amount,
                                                         comment=comment)

                            if report:
                                reports.append(report)

                        elif asset_account and (not asset_account_for_donate
                                                ):  # Если нет кому донатить
                            msg = self.bot_msg.NoProfileForDonate[
                                lng] + ' ' + target.upper()
                            self.tg.send_message(chat_id, msg, delete=True)

                for amount, report in reports:
                    # report
                    msg = ''.join([' +', amount, report])
                    self.tg.send_message(chat_id,
                                         reply_username + msg,
                                         delete=True)
                    if self.bot_menu.users_tg[user_id].get("report", True):
                        self.tg.send_message(
                            user_id, 'donate to ' + reply_username + msg)
                    if self.bot_menu.users_tg[reply_id].get("report", True):
                        self.tg.send_message(
                            reply_id, 'received from ' + user_name + msg)

                if not flag:
                    self.tg.send_message(chat_id,
                                         self.bot_msg.InvestorNot[lng],
                                         delete=True)

    ##### ##### HELP ##### #####

    def help_intro(self, message):
        msg = 'https://golos.id/ru--blokcheijn/@ksantoprotein/tip23bot-telegramm-bot-dlya-laikov-avtokleminga-i-igr'
        self.tg.send_message(message["chat"]["id"], msg)

    def help_reg(self, message):
        msg = 'https://golos.id/ru--blokcheijn/@ksantoprotein/tip23bot-registraciya'
        self.tg.send_message(message["chat"]["id"], msg)

    ##### ##### GET ##### #####

    def get_language(self, user_id):
        if user_id in self.bot_menu.users_tg:
            lng = self.bot_menu.users_tg[user_id].get("language", 'Russian')
        else:
            lng = 'Russian'
        return lng

    def get_chats(self, chat_list):
        chats = []
        for chat_id in chat_list:
            tx = self.tg.getChat(str(chat_id))
            if tx:
                chat = ''.join(
                    ['@',
                     tx.get("username", ''), ':',
                     tx.get("title", '')])
                chats.append(chat)
            else:
                print('error in chat', chat_id)
                chats.append('hidden')
        return chats

    def get_params_message(self, message, type):
        user_id = str(message["chat"]["id"])
        lng = self.get_language(user_id)
        keyboard = self.bot_menu.state[type]["keyboard"]
        db = self.bot_menu.users_tg[user_id]
        return ([user_id, lng, keyboard, db])

    def get_params_chat(self, message):
        user_id = str(message["from"]["id"])
        chat_id = str(message["chat"]["id"])
        lng = self.get_language(user_id)

        #db = self.bot_menu.users_tg[user_id]
        return ([user_id, chat_id, lng])

    def get_url_from_reply_text(self, reply_text, sign):
        lines = reply_text.split()
        authors = []
        for line in lines:
            if 'https://' == line[:8]:
                url = line
                response = self.golos.rpc.http.get(url, timeout=3)
                if response.ok:

                    text = str(response.text)
                    if sign + ':' in text:
                        for i in range(len(text)):
                            if sign + ':' == text[i:i + len(sign + ':')]:
                                raw = text[i:].split(':')[1]
                                author = []
                                if raw[0] in list(
                                        'abcdefghijklmnopqrstuvwxyz'):
                                    author.append(raw[0])
                                    for litter in raw[1:]:
                                        if litter in list(
                                                'abcdefghijklmnopqrstuvwxyz0123456789.-'
                                        ):
                                            author.append(litter)
                                        else:
                                            break
                                authors.append([''.join(author), url])

        if len(authors) > 0:
            print(sign, authors[0])
            return authors[0]
        return ([False, False])

    ##### ##### ##### ##### #####

    def language(self, message):
        lng = message["text"]
        user_id = str(message["chat"]["id"])
        if lng in ['Russian', 'English']:
            self.bot_menu.users_tg[user_id]["language"] = lng

    def report(self, message):
        type_report = True if message["text"] == 'On' else False
        user_id = str(message["chat"]["id"])
        self.bot_menu.users_tg[user_id].setdefault("report", True)
        self.bot_menu.users_tg[user_id]["report"] = type_report
Ejemplo n.º 7
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api


print('connect')
b4 = Api()
print('try call')


tx = b4.get_witness_count()

pprint(tx)
input()
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

account = 'ksantoprotein'
type_op = ['award']
age = 100 * 24 * 60 * 60  #aka sec

tx = b4.get_account_history(account, type_op=type_op, age=age)
print('find', len(tx))

input('end')
Ejemplo n.º 9
0
from exchange.Exchange import Exchange
#Библиотека для работы с БЧ VIZ
from tvizbase.api import Api

decimal.getcontext().rounding = 'ROUND_HALF_UP'
#Загрузка настроек из файла
path = os.path.dirname(__file__)
if path == '':
    path = '.'
with open(path + '/settings.json', 'r') as sett_file:
    settings = json.load(sett_file)

#Подключение к базе redis
redis = redis.Redis(db=settings['redis_db'])
#Подключение к БЧ VIZ
viz = Api()
last_block_num = viz.get_dynamic_global_properties()['head_block_number']
redis.set('viz_last_block_num', last_block_num)

viz_balance = 2000000
usdt_balance = 2100
rate = decimal.Decimal(
    usdt_balance / (settings['exchange_ratio'] * viz_balance)).quantize(
        decimal.Decimal('1.' + '0' * settings['rate_precision']))
settings['viz_limit_max'] = decimal.Decimal(
    float(viz_balance) * (1 - (1 - settings['viz_limit_percent'])**float(
        settings['exchange_ratio']))).quantize(
            decimal.Decimal('1.' + '0' * settings['viz_precision']))
settings['usdt_limit_max'] = decimal.Decimal(
    float(usdt_balance) * ((1 + settings['usdt_limit_percent']
                            )**float(1 / settings['exchange_ratio']) - 1) +
Ejemplo n.º 10
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_account_count()
print(tx)

input()
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

account = 'ksantoprotein'
wif = '5...'

witnesses = ['solox', 'lex', 'lexai']
approve = True

for witness in witnesses:
    tx = b4.get_accounts([account])[0]
    print(tx["name"], 'witness:', tx["witness_votes"], 'proxy:', tx["proxy"])

    input('ready?')

    tx = b4.account_witness_vote(account, witness, wif, approve=approve)
    pprint(tx)

input()
Ejemplo n.º 12
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

to = 'sci-populi'
amount = '0.001'
from_account = 'ksantoprotein'
wif = '5...'

tx = b4.transfer_to_vesting(to, amount, from_account, wif)
pprint(tx)
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api


print('connect')
b4 = Api()
print('try call')

from_account = 'u39.pom'
to_account = 'ksantoprotein'
wif = '5...'

tx = b4.set_withdraw_vesting_route(from_account, to_account, wif)
pprint(tx)
input()
Ejemplo n.º 14
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_all_accounts()
file = 'get_all_accounts.csv'
with open(file, 'w', encoding='utf8') as f:
    for login, value in tx.items():
        f.write(';'.join([login, json.dumps(value) + '\n']))

input('next')
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

creator = 'ksantoprotein'
wif = '5...'
json_metadata = {"profile": {}}

login = '******'
password = '******'

#tx = b4.account_create(login, password, creator, wif, fee = 1.0)
#pprint(tx)

tx = b4.account_create(login, password, creator, wif, delegation=True)
pprint(tx)
tx = b4.delegate_vesting_shares(login, 0, creator, wif)
pprint(tx)

input()
Ejemplo n.º 16
0
from exchange.Exchange import Exchange
#Библиотека для работы с БЧ VIZ
from tvizbase.api import Api

#Загрузка настроек из файла
path = os.path.dirname(__file__)
if path == '':
    path = '.'
with open(path + '/settings.json', 'r') as sett_file:
    settings = json.load(sett_file)

decimal.getcontext().rounding = 'ROUND_HALF_UP'
#Подключение к базе redis
redis = redis.Redis(db=settings['redis_db'])
#Подключение к БЧ VIZ
viz = Api()
#Создание класса обменника
exchange = Exchange(settings, viz=viz, redis=redis)
#Получение номера последнего обработанного блока
try:
    last_block_num = int(redis.get('viz_last_block_num'))
except:
    exchange.send_alert('Ошибка чтения из базы данных. Скрипт остановлен.')
    sys.exit('Ошибка чтения из базы данных. Скрипт остановлен.')
#Публикация настроек из файла в блокчейн
exchange.post_status()
exchange.post_new_rate(exchange.viz_balance, exchange.usdt_balance)
#Получение и обработка новых блоков каждые 3 секунды
one_minute = three_minute = datetime.timestamp(datetime.now())
while (True):
    block_num = viz.get_dynamic_global_properties()['head_block_number']
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api


print('connect')
b4 = Api()
print('try call')


initiator = 'ksantoprotein'
receiver = 'ksantoprotein'
invite_secret = '5...'
wif = '5...'

tx = b4.claim_invite_balance(initiator, receiver, invite_secret, wif)
pprint(tx)
input()



Ejemplo n.º 18
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

block = 3058791

tx = b4.get_block(block)

pprint(tx)
input()
Ejemplo n.º 19
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

public_key = 'VIZ7tnDdbUmjT89YQsokHagcjwzVN1FPWL86wUe6S3TNUgJaYvn2i'

tx = b4.get_key_references(public_key)

print(tx)
input()
Ejemplo n.º 20
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_invites_list()

for id in tx:
    tx = b4.get_invite(id)
    print(tx["creator"], tx["balance"])

input()
import json
import os
import sys
from datetime import datetime

from tvizbase.api import Api

#Loading settings from the json file
with open(os.path.dirname(__file__) + '/settings.json', 'r') as sett_file:
    settings = json.load(sett_file)
viz = Api()
#Getting the head block number from the blockchain
block_num = viz.get_dynamic_global_properties()['head_block_number']
#Number of blocks for energy recovery
block_count = (20 * 60 * 24 / 20) * settings['award_percent']
#Blcok delay for posting in the blockchain
block_count -= 2
#Comparing the head block number with the number of the last operation
if block_num <= settings['last_block_num'] + block_count:
    sys.exit()
#Getting account data
account = viz.get_accounts([settings['viz_account']['login']])[0]
receiver = 'committee'
#Calculating percentage of the award
award_percent = round(settings['award_percent'] * 100 *
                      settings['award_base'] / account['SHARES'])
#Sending award in the blockchain
res = viz.award(settings['viz_account']['login'], receiver, award_percent,
                settings['viz_account']['key'])
if res == False:
    sys.exit()
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

start = 'a'
limit = '100'
tx = b4.lookup_witness_accounts(start, limit)

pprint(tx)
input()
Ejemplo n.º 23
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_chain_properties()

pprint(tx)
input()
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

tx = b4.get_dynamic_global_properties()
pprint(tx)
input()
Ejemplo n.º 25
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

initiator = 'ksantoprotein'
receiver = 'ksantoprotein'
energy = 0
wif = '5...'

memo = 'test'

tx = b4.award(initiator, receiver, energy, wif, memo=memo)
pprint(tx)
input()
Ejemplo n.º 26
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api


print('connect')
b4 = Api()
print('try call')

secret = '5...'
key = b4.key.get_public(secret)
print(key)


#key = 'VIZ5oDuGMa3DD2YPeDci5ZuuswaMqWh9Zw2qtXPVxABgGNF65hjTv'
tx = b4.get_invite(key)
pprint(tx)


input('next?')


id = 5
tx = b4.get_invite(id)
pprint(tx)


input('end')
Ejemplo n.º 27
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

block = 3058791

tx = b4.get_ops_in_block(block)

pprint(tx)
input()
Ejemplo n.º 28
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

to = 'sci-populi'
amount = '0.001'
memo = 'test'

from_account = 'ksantoprotein'
wif = '5...'
tx = b4.transfer(to, amount, from_account, wif, memo=memo)
pprint(tx)
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api


print('connect')
b4 = Api()
print('try call')


creator = 'ksantoprotein'
wif = '5...'
balance = 1.100

psw = 'P5...'
keys = b4.key.get_keys(creator, psw)
invite_key = keys["public"]["active"]


tx = b4.create_invite(creator, balance, invite_key, wif)
pprint(tx)

if tx:
	with open('invite_create.csv', 'a', encoding = 'utf8') as f:
		f.write(keys["private"]["active"] + ' ' + str(balance) + '\n')

input()
Ejemplo n.º 30
0
# -*- coding: utf-8 -*-

import json
from pprint import pprint

from tvizbase.api import Api

print('connect')
b4 = Api()
print('try call')

id = 'viz_contract'
payload = {"app": 'thallid', "spell": 'fireball', "damage": 100}

account = 'ksantoprotein'
wif = '5...'

tx = b4.custom(id, payload, account, wif)
pprint(tx)
input()