Exemple #1
0
from LaylaRobot.events import register
from LaylaRobot import telethn as tbot
TMP_DOWNLOAD_DIRECTORY = "./"
from telethon import events
import os
from PIL import Image
from datetime import datetime
from telegraph import Telegraph, upload_file, exceptions
Hero = "Layla"
telegraph = Telegraph()
r = telegraph.create_account(short_name=Hero)
auth_url = r["auth_url"]


@register(pattern="^/t(m|xt) ?(.*)")
async def _(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
        if input_str == "m":
            downloaded_file_name = await tbot.download_media(
                r_message, TMP_DOWNLOAD_DIRECTORY)
            end = datetime.now()
            ms = (end - start).seconds
            h = await event.reply("Downloaded to {} in {} seconds.".format(
                downloaded_file_name, ms))
            if downloaded_file_name.endswith((".webp")):
Exemple #2
0
"""@telegraph Utilities
Available Commands:
/telegraph media as reply to a media
/telegraph text as reply to a large text"""
import os
from datetime import datetime

from PIL import Image
from telegraph import Telegraph, exceptions, upload_file
from DaisyX.services.telethon import tbot as borg
from telethon import events

telegraph = Telegraph()
r = telegraph.create_account(short_name="DaisyX")
auth_url = r["auth_url"]

#Will change later
TMP_DOWNLOAD_DIRECTORY = "./"

BOTLOG = False


@borg.on(events.NewMessage(pattern="/telegraph (media|text) ?(.*)"))
async def _(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
from pyrogram import MessageHandler, Filters
from telegram import Bot, ParseMode
from secrets import bot_token
import re
import requests
from bs4 import BeautifulSoup
from telegraph import utils as tutils, upload as tupload
from telegraph import Telegraph
import shutil

bot = Bot(bot_token)
telegraph = Telegraph()

telegraph.create_account(short_name='@Lor3m', author_name='@Lor3m')


def new_post(client, message):
    post = message.text
    link = re.findall(r'(https?://\S+)', post)[-1]

    parsed = requests.get(link).text

    page = BeautifulSoup(parsed, features="html.parser")
    try:
        title = page.find('div', class_='bdaia-post-title').find('h1').next
    except AttributeError:
        title = page.find('h1', class_='post-title')
    content = page.find('div', class_='bdaia-post-content')
    image_url = re.findall(
        r'(https?://\S+)',
        page.find('a',
Exemple #4
0
import datetime
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from telegraph import Telegraph
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from wolf import bot as borg
from wolf.utils import admin_cmd
from wolf import CMD_HELP
telegraph = Telegraph()
mee = telegraph.create_account(short_name="shivam")


@borg.on(admin_cmd(pattern="recognize ?(.*)"))
async def _(event):
    if event.fwd_from:
        return
    if not event.reply_to_msg_id:
        await event.edit("Reply to any user's media message.")
        return
    reply_message = await event.get_reply_message()
    if not reply_message.media:
        await event.edit("reply to media file")
        return
    chat = "@Rekognition_Bot"
    sender = reply_message.sender
    if reply_message.sender.bot:
        await event.edit("Reply to actual users message.")
        return
    async with event.client.conversation(chat) as conv:
        try:
            response = conv.wait_event(
Exemple #5
0
from SaitamaRobot.events import register
from SaitamaRobot import telethn as tbot
TMP_DOWNLOAD_DIRECTORY = "tg-File/"
from telethon import events
import os
from PIL import Image
from datetime import datetime
from telegraph import Telegraph, upload_file, exceptions
babe = "SaitamaRobot"
telegraph = Telegraph()
r = telegraph.create_account(short_name=babe)
auth_url = r["auth_url"]


@register(pattern="^/t(m|t) ?(.*)")
async def _(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
        if input_str == "m":
            downloaded_file_name = await tbot.download_media(
                r_message,
                TMP_DOWNLOAD_DIRECTORY
            )
            end = datetime.now()
            ms = (end - start).seconds
            h = await event.reply("Downloaded to {} in {} seconds.".format(downloaded_file_name, ms))
from main_startup.config_var import Config
from main_startup.core.decorators import friday_on_cmd
from main_startup.core.startup_helpers import run_cmd
from main_startup.helper_func.basic_helpers import edit_or_reply, get_text
from main_startup.helper_func.plugin_helpers import (
    convert_to_image,
    convert_vid_to_vidnote,
    generate_meme,
)

glitcher = ImageGlitcher()
DURATION = 200
LOOP = 0

telegraph = Telegraph()
r = telegraph.create_account(short_name="FridayUserBot")
auth_url = r["auth_url"]


@friday_on_cmd(
    ["ytc"],
    cmd_help={
        "help": "Create Youtube Comment!",
        "example": "{ch}ytc (reply to Someone) (text comment)",
    },
)
async def ytc(client, message):
    pablo = await edit_or_reply(message, "`Processing...`")
    comment = get_text(message)
    if not comment:
        await pablo.edit("`Provide Some Text For Comment!`")
# Originally By @DeletedUser420
# Ported - @StarkxD

import asyncio
import os
import shlex
from typing import Tuple

from telegraph import Telegraph

from fridaybot import CMD_HELP
from fridaybot.Configs import Config
from fridaybot.utils import friday_on_cmd

telegraph = Telegraph()
tgnoob = telegraph.create_account(short_name="Friday 🇮🇳")


async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
    """ run command in terminal """
    args = shlex.split(cmd)
    process = await asyncio.create_subprocess_exec(
        *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()
    return (
        stdout.decode("utf-8", "replace").strip(),
        stderr.decode("utf-8", "replace").strip(),
        process.returncode,
        process.pid,
    )
Exemple #8
0
from Luna import tbot, CMD_HELP
from Luna.events import register
import os
from datetime import datetime

dir = './'
from PIL import Image
from telegraph import Telegraph, exceptions, upload_file

telegraph = Telegraph()
r = telegraph.create_account('Luna')
auth_url = r["auth_url"]


@register(pattern="^/t(m|text) ?(.*)")
async def tele(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
        if input_str == "m":
            downloaded_file_name = await tbot.download_media(r_message, dir)
            if downloaded_file_name.endswith((".webp")):
                resize_image(downloaded_file_name)
            try:
                media_urls = upload_file(downloaded_file_name)
            except exceptions.TelegraphException as exc:
                await event.reply("ERROR: " + str(exc))
Exemple #9
0
By :- Jaskaran ^_^ 
Telegram :- @Denzid

"""

from asyncio import wait
import time
import gc
from telegraph import Telegraph
from bs4 import BeautifulSoup as bs
import requests
from telethon import events
from userbot.utils import admin_cmd

telegraph = Telegraph()
telegraph.create_account(short_name='zeroc')
chat_ids = [596701090, 517742107]
csclist = [
    'ACG', 'ATT', 'BST', 'CCT', 'GCF', 'LRA', 'SPR', 'TFN', 'TMB', 'USC',
    'VMU', 'VZW', 'XAA', 'XAS', 'AFG', 'TMC', 'TTR', 'DRE', 'MOB', 'MAX',
    'TRG', 'SEB', 'PRO', 'TEB', 'BHT', 'GBL', 'BGL', 'MTL', 'VVT', 'CAM',
    'CAU', 'DHR', 'CRO', 'TWO', 'VIP', 'CYV', 'CYO', 'ETL', 'O2C', 'TMZ',
    'VDC', 'EGY', 'XEF', 'BOG', 'FTM', 'SFR', 'DBT', 'XEG', 'DDE', 'VIA',
    'DTM', 'VD2', 'EUR', 'COS', 'VGR', 'XEH', 'TMH', 'PAN', 'VDH', 'XSE',
    'XID', 'THR', 'MID', 'TSI', 'MET', '3IE', 'VDI', 'ILO', 'CEL', 'PTR',
    'PCL', 'ITV', 'HUI', 'TIM', 'OMN', 'WIN', 'SKZ', 'AFR', 'KEN', 'BTC',
    'LUX', 'VIM', 'MBM', 'XME', 'MRU', 'TMT', 'MAT', 'MWD', 'PHN', 'DNL',
    'TNL', 'VDF', 'ECT', 'NEE', 'TEN', 'ATO', 'PAK', 'GLB', 'XTC', 'SMA',
    'XTE', 'XEO', 'DPL', 'IDE', 'PLS', 'PRT', 'TPL', 'MEO', 'OPT', 'TPH',
    'TCL', 'ROM', 'COA', 'ORO', 'CNX', 'SER', 'ACR', 'WTL', 'XFU', 'TSR',
    'MSR', 'TOP', 'ORX', 'TMS', 'SIO', 'MOT', 'SIM', 'XFE', 'XFA', 'XFV',
Exemple #10
0
from telegraph import Telegraph

telegraph = Telegraph()
telegraph.create_account(short_name=input("Codex Mirror Bot : "))

print(f"Your Telegra.ph token ==>  {telegraph.get_access_token()}")
Exemple #11
0
from telegraph import Telegraph

telegraph = Telegraph()
telegraph.create_account(
    short_name=input("Enter a username for your Telegra.ph : "))

print(f"Your Telegra.ph token ==>  {telegraph.get_access_token()}")
import lyricspy
import threading
import markdown2
from config import bot
from telegraph import Telegraph
from amanobot.loop import MessageLoop
from amanobot.namedtuple import InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardMarkup
import re

telegraph = Telegraph()
telegraph.create_account(short_name='LyricsPyRobot', author_name='amn')


def send_te(a, b):
    response = telegraph.create_page(a['musica'],
                                     html_content=markdown2.markdown(
                                         b.replace('\n', '<br>')),
                                     author_name=a["autor"],
                                     author_url=a["link"])
    return response


def handle_thread(*args, **kwargs):
    t = threading.Thread(target=handle, args=args, kwargs=kwargs)
    t.daemon = True
    t.start()


def handle(msg):
    if 'text' in msg:
        if msg['text'] == '/start':
Exemple #13
0
# Originally By @DeletedUser420
# Ported - @StarkxD

import asyncio
import os
import shlex
from typing import Tuple

from telegraph import Telegraph

from userbot.Config import Config
from userbot.utils import lightning_cmd

telegraph = Telegraph()
tgnoob = telegraph.create_account(short_name="Lighting")


async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
    """ run command in terminal """
    args = shlex.split(cmd)
    process = await asyncio.create_subprocess_exec(
        *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    stdout, stderr = await process.communicate()
    return (
        stdout.decode("utf-8", "replace").strip(),
        stderr.decode("utf-8", "replace").strip(),
        process.returncode,
        process.pid,
    )

Exemple #14
0
print("[INFO]: STARTING USERBOT CLIENT")
app2.start()

print("[INFO]: GATHERING PROFILE INFO")
x = app.get_me()
y = app2.get_me()

BOT_ID = x.id
BOT_NAME = x.first_name + (x.last_name or "")
BOT_USERNAME = x.username
BOT_MENTION = x.mention
BOT_DC_ID = x.dc_id

USERBOT_ID = y.id
USERBOT_NAME = y.first_name + (y.last_name or "")
USERBOT_USERNAME = y.username
USERBOT_MENTION = y.mention
USERBOT_DC_ID = y.dc_id

if USERBOT_ID not in SUDOERS:
    SUDOERS.append(USERBOT_ID)

telegraph = Telegraph()
telegraph.create_account(short_name=BOT_USERNAME)


async def eor(msg: Message, **kwargs):
    func = msg.edit_text if msg.from_user.is_self else msg.reply
    spec = getfullargspec(func.__wrapped__).args
    return await func(**{k: v for k, v in kwargs.items() if k in spec})
Exemple #15
0
from LightYagami.events import register
from LightYagami import telethn as tbot
TMP_DOWNLOAD_DIRECTORY = "./"
from telethon import events
import os
from PIL import Image
from datetime import datetime
from telegraph import Telegraph, upload_file, exceptions
kira = "LightYagami"
telegraph = Telegraph()
r = telegraph.create_account(short_name=kira)
auth_url = r["auth_url"]


@register(pattern="^/t(m|t) ?(.*)")
async def _(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
        if input_str == "m":
            downloaded_file_name = await tbot.download_media(
                r_message, TMP_DOWNLOAD_DIRECTORY)
            end = datetime.now()
            ms = (end - start).seconds
            h = await event.reply("Downloaded to {} in {} seconds.".format(
                downloaded_file_name, ms))
            if downloaded_file_name.endswith((".webp")):
Exemple #16
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask, Response, redirect, request
from sqlite3 import Error
import sqlite3
import requests
from telegraph import Telegraph

telegraph = Telegraph()
telegraph.create_account(short_name='Барахолка')
app = Flask(__name__)
BOT_URL = 'https://api.telegram.org/bot{0}/'.format(
    open('secrets/bot_token', 'r').read()[:-1])
FILE_URL = 'https://api.telegram.org/file/bot{0}/'.format(
    open('secrets/bot_token', 'r').read()[:-1])
database_path = r"database/db.sqlite"
possible_hashtags = set(
    "#лбкиїв_компліт #лбкиїв_підвіси #лбкиїв_колеса #лбкиїв_дека #лбкиїв_інше #лбкиїв_захист"
    .split(' '))


def create_connection(db_file):
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)
    return conn

Exemple #17
0
from MashaRoBot.events import register
from MashaRoBot import telethn as tbot
TMP_DOWNLOAD_DIRECTORY = "./"
from telethon import events
import os
from PIL import Image
from datetime import datetime
from telegraph import Telegraph, upload_file, exceptions
darkprince = "MASHA"
telegraph = Telegraph()
r = telegraph.create_account(short_name=darkprince)
auth_url = r["auth_url"]


@register(pattern="^/t(m|xt) ?(.*)")
async def _(event):
    if event.fwd_from:
        return
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
        start = datetime.now()
        r_message = await event.get_reply_message()
        input_str = event.pattern_match.group(1)
        if input_str == "m":
            downloaded_file_name = await tbot.download_media(
                r_message, TMP_DOWNLOAD_DIRECTORY)
            end = datetime.now()
            ms = (end - start).seconds
            h = await event.reply("Downloaded to {} in {} seconds.".format(
                downloaded_file_name, ms))
            if downloaded_file_name.endswith((".webp")):
# Originally By @DeletedUser420
# Ported - @StarkxD

import asyncio
import os
import shlex
from typing import Tuple

from telegraph import Telegraph

from WhiteEyeUserBot import CMD_HELP
from WhiteEyeUserBot.Configs import Config
from WhiteEyeUserBot.utils import WhiteEye_on_cmd

telegraph = Telegraph()
tgnoob = telegraph.create_account(short_name="WhiteEye 🇮🇳")


async def runcmd(cmd: str) -> Tuple[str, str, int, int]:
    """ run command in terminal """
    args = shlex.split(cmd)
    process = await asyncio.create_subprocess_exec(
        *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()
    return (
        stdout.decode("utf-8", "replace").strip(),
        stderr.decode("utf-8", "replace").strip(),
        process.returncode,
        process.pid,
    )
Exemple #19
0
# rewritten by @saravanakrish

from telegraph import Telegraph
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError

from userbot.utils import admin_cmd

telegraph = Telegraph()
mee = telegraph.create_account(short_name="tamilbot")


@borg.on(admin_cmd(pattern="purl ?(.*)"))
async def _(event):
    if event.fwd_from:
        return
    if not event.reply_to_msg_id:
        await event.reply("**Reply to any document.**")
        return
    reply_message = await event.get_reply_message()
    chat = "@FiletolinkTGbot"
    reply_message.sender
    await eor(event, "**Making public url...**")
    async with event.client.conversation(chat) as conv:
        try:
            response = conv.wait_event(
                events.NewMessage(incoming=True, from_users=1011636686))
            await event.client.forward_messages(chat, reply_message)
            response = await response
        except YouBlockedUserError:
            await eor(event,
Exemple #20
0
from telegraph import Telegraph

from views import page_pattern
from data.structures import Talent, Talent2, Build

from utils.fetcher import check_image, HOTSDOG_URL

# from html_telegraph_poster import TelegraphPoster
# t = TelegraphPoster()

MY_NAME = 'hotsassistbot'

telegraph = Telegraph()
telegraph.create_account(short_name=MY_NAME)


def make_page(blizzard_hero, build_idx):

    img = blizzard_hero.hero.image
    alt_img = (f'{HOTSDOG_URL}/img/hero_full/'
               f'{blizzard_hero.hero.en_name.lower()}.png')

    print(f"Check image: {check_image(img)}")

    if not check_image(img):
        hero = blizzard_hero.hero._replace(image=alt_img)
        blizzard_hero = blizzard_hero._replace(hero=hero)

    print(f"Image now: {blizzard_hero.hero.image}")

    rows = ''
Exemple #21
0
                  api_id=API_ID,
                  api_hash=API_HASH)
else:
    print("[INFO]: LOADING USERBOT CLIENT")
    app2 = Client(SESSION_STRING, api_id=API_ID, api_hash=API_HASH)

# Bot client
print("[INFO]: LOADING BOT CLIENT")
app = Client("wbb", bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)
# ARQ client
print("[INFO]: LOADING ARQ")
arq = ARQ(ARQ_API_URL, ARQ_API_KEY)
# Telegraph client
print("[INFO]: LOADING TELEGRAPH")
telegraph = Telegraph()
telegraph.create_account(short_name="wbb")

BOT_ID = 0
BOT_NAME = ""
BOT_USERNAME = ""
BOT_MENTION = ""
BOT_DC_ID = 0
USERBOT_ID = 0
USERBOT_NAME = ""
USERBOT_USERNAME = ""
USERBOT_DC_ID = 0
USERBOT_MENTION = ""


def get_info(app, app2):
    global BOT_ID, BOT_NAME, BOT_USERNAME, BOT_DC_ID, BOT_MENTION
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.

import os

from telegraph import Telegraph
from telegraph import upload_file as upl

from . import *

# --------------------------------------------------------------------#
telegraph = Telegraph()
r = telegraph.create_account(short_name="Ultroid")
auth_url = r["auth_url"]
# --------------------------------------------------------------------#


@callback("alvcstm")
@owner
async def alvcs(event):
    await event.edit(
        "Customise your {}alive. Choose from the below options -".format(
            HNDLR),
        buttons=[
            [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="alvtx")],
            [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")],
            [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")],
            [Button.inline("« Bᴀᴄᴋ", data="setter")],
Exemple #23
0
            exit(1)
    finally:
        cur.close()
        conn.close()

LOGGER.info("Generating USER_SESSION_STRING")
app = Client(':memory:',
             api_id=int(TELEGRAM_API),
             api_hash=TELEGRAM_HASH,
             bot_token=BOT_TOKEN)

# Generate Telegraph Token
sname = ''.join(random.SystemRandom().choices(string.ascii_letters, k=8))
LOGGER.info("Generating TELEGRAPH_TOKEN using '" + sname + "' name")
telegraph = Telegraph()
telegraph.create_account(short_name=sname)
telegraph_token = telegraph.get_access_token()

try:
    STATUS_LIMIT = getConfig('STATUS_LIMIT')
    if len(STATUS_LIMIT) == 0:
        raise KeyError
    else:
        STATUS_LIMIT = int(getConfig('STATUS_LIMIT'))
except KeyError:
    STATUS_LIMIT = None
try:
    MEGA_API_KEY = getConfig('MEGA_API_KEY')
except KeyError:
    logging.warning('MEGA API KEY not provided!')
    MEGA_API_KEY = None
Exemple #24
0
async def cria_site_telegraph(msg):
    conexao_sqlite = sqlite3.connect('bot_database.db')
    conexao_sqlite.row_factory = sqlite3.Row
    cursor_sqlite = conexao_sqlite.cursor()
    try:
        if msg['chat']['type'] == 'supergroup':
            try:
                grupo = f"https://t.me/{msg['chat']['username']}"
            except:
                grupo = f"Secreto: {msg['chat']['title']}"
                pass
            try:
                usuario = msg['from']['username']
            except:
                usuario = f"@{msg['from']['id']}({msg['from']['first_name']})"
                pass
            data = datetime.now().strftime('%d/%m/%Y %H:%M')
            chat_type = msg['chat']['type']
            chat_id = msg['chat']['id']
            texto = msg['text']
            if texto == 'links':
                cursor_sqlite.execute("""SELECT * FROM telegraph_sites""")
                resultados = cursor_sqlite.fetchall()
                a = await bot.sendMessage(
                    chat_id,
                    f"🤖 {msg['from']['first_name']} tenho {str(len(resultados))} páginas criadas, vou exibir elas em ordem com uma pausa de 3 segundos...",
                    reply_to_message_id=msg['message_id'])
                for resultado in resultados:
                    link = resultado['link']
                    await bot.editMessageText(
                        (msg['chat']['id'], a['message_id']), link)
                    time.sleep(3)

            if 'photo' in msg.get(
                    'reply_to_message') and 'web' in texto.split()[0]:
                titulo = texto.split()[1]
                separador = ' \n'
                conte = texto.split()[2:]
                conteudo = separador.join(map(str, conte))
                id_foto = msg.get('reply_to_message')['photo'][0]['file_id']
                await bot.download_file(id_foto, 'arquivos/criar_site.jpg')

                PATH = 'arquivos/criar_site.jpg'
                im = pyimgur.Imgur(token_imgur)
                uploaded_image = im.upload_image(PATH, title=titulo)
                link_imagem = uploaded_image.link
                conteudo_html = f'<img src="{link_imagem}"><p>{conteudo}</p><br><br><br><br><a href="https://t.me/{bot_username}?start=start">Telegram: @{bot_username}</a>'
                telegraph = Telegraph()
                a = telegraph.create_account(short_name='manicomio')
                response = telegraph.create_page(titulo,
                                                 html_content=conteudo_html)
                link_final = 'https://telegra.ph/{}'.format(response['path'])
                print(f"Usuário criou um site no telegra.ph: {link_final}")
                await bot.sendMessage(
                    chat_id,
                    f"🤖 {msg['from']['first_name']} acabei seu site:{link_final}",
                    reply_to_message_id=msg['message_id'])
                os.remove('arquivos/criar_site.jpg')
                # tabela do armazenamento dos sites telegraph
                cursor_sqlite.execute(
                    f"""INSERT INTO telegraph_sites (int_id, grupo, tipo_grupo, id_grupo, usuario, id_usuario, data,titulo,texto,imagem,link)VALUES(null,'{grupo}','{chat_type}','{chat_id}','@{usuario}','{msg['from']['id']}','{data}','{titulo}','{conteudo}','{link_imagem}','{link_final}')"""
                )
                conexao_sqlite.commit()
                conexao_sqlite.close()
    except Exception as e:
        pass
import os
from datetime import datetime

from PIL import Image
from telegraph import Telegraph, exceptions, upload_file

from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY, bot
from userbot.events import register

telegraph = Telegraph()
r = telegraph.create_account(short_name="telegraph")
auth_url = r["auth_url"]


@register(outgoing=True, pattern=r"^\.tg (m|t)$")
async def telegraphs(graph):
    await graph.edit("`Sedang Memproses... Sabar ya bentar juga muncul😁`")
    if not graph.text[0].isalpha() and graph.text[0] not in (
            "/", "#", "@", "!"):
        if graph.fwd_from:
            return
        if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
            os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
        if graph.reply_to_msg_id:
            start = datetime.now()
            r_message = await graph.get_reply_message()
            input_str = graph.pattern_match.group(1)
            if input_str == "m":
                downloaded_file_name = await bot.download_media(
                    r_message, TEMP_DOWNLOAD_DIRECTORY
                )
Exemple #26
0

import asyncio
import random, re
import datetime
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from telegraph import Telegraph
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from LEGENDX import CMD_HELP
from LEGENDX.utils import admin_cmd
from var import Var
telegraph = Telegraph()
mee = telegraph.create_account(short_name="yohohehe")


@borg.on(admin_cmd(pattern="recognize ?(.*)"))
async def _(event):
    if event.fwd_from:
        return 
    if not event.reply_to_msg_id:
       await event.edit("Reply to any user's media message.")
       return
    reply_message = await event.get_reply_message() 
    if not reply_message.media:
       await event.edit("reply to media file")
       return
    chat = "@Rekognition_Bot"
    sender = reply_message.sender
    if reply_message.sender.bot:
       await event.edit("Reply to actual users message.")
         raise ParserException("文章article解析错误", url)
     imgs = article.find_all("img")
     task = list(relink(img) for img in imgs)  ## data-src -> src
     for _ in article.find_all("h1"):  ## h1 -> h3
         _.name = "h3"
     for _ in article.find_all("span"):  ## remove span
         _.unwrap()
     for s in ["p", "figure", "figcaption"]:  ## clean tags
         for _ in article.find_all(s):
             _.attrs = {}
     telegraph = Telegraph()
     await asyncio.gather(*task)
     result = "".join([
         i.__str__() for i in article.contents
     ])  ## div rip off, cannot unwrap div so use str directly
     telegraph.create_account("bilifeedbot")
     graphurl = telegraph.create_page(
         title=title,
         html_content=result,
         author_name=f.user,
         author_url=f"https://space.bilibili.com/{f.uid}",
     ).get("url")
     logger.info(f"生成页面: {graphurl}")
     logger.info(f"文章缓存: {f.read_id}")
     if cache := await read_cache.get_or_none(None, query):
         cache.graphurl = graphurl
         await cache.save(update_fields=["graphurl", "created"])
     else:
         await read_cache(read_id=f.read_id, graphurl=graphurl).save()
 f.extra_markdown = f"[{escape_markdown(title)}]({graphurl})"
 f.replycontent = await reply_parser(client, f.read_id, f.reply_type)
Exemple #28
0
async def _(event):
    if not event.is_private:
        return
    tata = event.pattern_match.group(1)
    data = tata.decode()
    meta = data.split("-", 1)[1]
    # print(meta)
    if "|" in meta:
        sender, chatid, msgid = meta.split("|")
    sender = int(sender.strip())
    if not event.sender_id == sender:
        await event.answer("You haven't send that command !")
        return

    num = 0
    chatid = int(chatid.strip())
    msgid = int(msgid.strip())
    to_check = get_email(event.sender_id)
    email = to_check["email"]
    hash = to_check["hash"]
    mails = tm.get_mailbox(email=email, email_hash=hash)
    if type(mails) is dict:
        for key, value in mails.items():
            if value == "There are no emails yet":
                await tbot.edit_message(chatid, msgid, "There are no emails yet.")
                return
    vector = len(mails)
    if num > vector - 1:
        num = 0
    # print(vector)
    # print(num)
    header = f"**#{num} **"
    from_mail = mails[int(num)]["mail_from"]
    subject = mails[int(num)]["mail_subject"]
    msg = mails[int(num)]["mail_text"]
    ttime = mails[int(num)]["mail_timestamp"]
    mail_id = mails[int(num)]["mail_id"]
    attch = int(mails[int(num)]["mail_attachments_count"])
    timestamp = ttime
    dt_object = datetime.fromtimestamp(timestamp)
    ttime = str(dt_object)

    header = f"**#{num} **"

    telegraph = Telegraph()
    telegraph.create_account(short_name="MissJuliaRobot")
    if subject == "":
        subject = "No Subject"

    headers = f"**FROM**: {from_mail}\n**TO**: {email}\n**DATE**: {ttime}\n**MAIL BODY**:\n\n{msg}"
    nheaders = headers.replace("\n", "<br />")
    final = markdown.markdown(nheaders)
    response = telegraph.create_page(subject, html_content=final)

    tlink = "https://telegra.ph/{}".format(response["path"])
    if not attch > 0:
        lastisthis = (
            f"{header}MAIL FROM: {from_mail}"
            + "\n"
            + f"TO: {email}"
            + "\n"
            + f"DATE: `{ttime}`"
        )
    else:
        lastisthis = (
            f"{header}MAIL FROM: {from_mail}"
            + "\n"
            + f"TO: {email}"
            + "\n"
            + f"DATE: `{ttime}`"
            + "\n\n"
            + "**The attachments will be send to you shortly !**"
        )
    await tbot.edit_message(
        chatid,
        msgid,
        lastisthis,
        link_preview=False,
        buttons=[
            [
                Button.url(
                    "Click here to read this mail",
                    url=f"{tlink}",
                ),
            ],
            [
                Button.inline(
                    "◀️",
                    data=f"checkinboxprev-{sender}|{num}|{chatid}|{msgid}",
                ),
                Button.inline("❌", data=f"stopcheckinbox-{sender}|{chatid}|{msgid}"),
                Button.inline(
                    "▶️",
                    data=f"checkinboxnext-{sender}|{num}|{chatid}|{msgid}",
                ),
            ],
            [
                Button.inline(
                    "Refresh 🔁",
                    data=f"refreshinbox-{sender}|{chatid}|{msgid}",
                )
            ],
        ],
    )
    if attch > 0:
        gg = get_attachments(mail_id)
        for i in gg:
            fname = i["name"]
            with open(fname, "w+b") as f:
                f.write(base64.b64decode((i["content"]).encode()))
            await tbot.send_file(chatid, file=fname)
            os.remove(fname)
Exemple #29
0
"""@telegraph Plugin For Lazy People
Available Commands:
.telegraph media as reply to a media
.telegraph text as reply to a large text"""
from telethon import events
import os
from PIL import Image
from datetime import datetime
from telegraph import Telegraph, upload_file, exceptions
from userbot.utils import admin_cmd

telegraph = Telegraph()
r = telegraph.create_account(short_name=Config.TELEGRAPH_SHORT_NAME)
auth_url = r["auth_url"]


@borg.on(admin_cmd("telegraph (media|text) ?(.*)"))
async def _(event):
    if event.fwd_from:
        return
    if Config.PRIVATE_GROUP_BOT_API_ID is None:
        await event.edit("Please set the required environment variable `PRIVATE_GROUP_BOT_API_ID` for this plugin to work")
        return
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    await borg.send_message(
        Config.PRIVATE_GROUP_BOT_API_ID,
        "Created New Telegraph account {} for the current session. \n**Do not give this url to anyone, even if they say they are from Telegram!**".format(auth_url)
    )
    optional_title = event.pattern_match.group(2)
    if event.reply_to_msg_id:
Exemple #30
0
import html
import textwrap
import bs4
import jikanpy
import requests
from telegraph import Telegraph
from inspect import getfullargspec

from pyrogram import Client, filters
from pyrogram.types import Message, Update, InlineKeyboardMarkup, InlineKeyboardButton

from hitsuki import pbot
from hitsuki.modules.tr_engine.strings import tld

telegraph = Telegraph()
telegraph.create_account(short_name='hitsuki')
info_btn = "More Information"
url = 'https://graphql.anilist.co'


airing_query = '''
    query ($id: Int,$search: String) { 
      Media (id: $id, type: ANIME,search: $search) { 
        id
        episodes
        title {
          romaji
          english
          native
        }
        siteUrl