Skip to content

Commit

Permalink
Welcomes + Screenshot without API
Browse files Browse the repository at this point in the history
Co-authored-by: Shrimadhav U K <[email protected]>
  • Loading branch information
Avinash Reddy and SpEcHiDe authored Aug 3, 2019
1 parent 30f980d commit b475696
Show file tree
Hide file tree
Showing 10 changed files with 243 additions and 56 deletions.
4 changes: 0 additions & 4 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,6 @@
"description": "Get your own APPID (API key)from https://api.openweathermap.org/data/2.5/weather",
"required": false
},
"SCREENSHOT_LAYER_ACCESS_KEY": {
"description": "Get your own ACCESS_KEY (API key) from http://api.screenshotlayer.com/api/capture",
"required": false
},
"BOTLOG": {
"description": "Incase you want to turn off logging, put this to false",
"value": "False"
Expand Down
7 changes: 0 additions & 7 deletions sample_config.env
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,6 @@ ___________PLOX_______REMOVE_____THIS_____LINE__________=True
API_KEY = "YOUR API KEY"
API_HASH = "YOUR API HASH"

#
# Screenshot Layer API Key for .screenshot command
# Get from https://screenshotlayer.com/
# Please refer to README for getting the key
#
SCREENSHOT_LAYER_ACCESS_KEY = ""

#
# OpenWeather Map API Key for .weather command
# Get from https://openweathermap.org/
Expand Down
4 changes: 3 additions & 1 deletion string_session.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
from userbot import API_KEY, API_HASH

print("""Please go-to my.telegram.org
Login using your Telegram account
Click on API Development Tools
Create a new application, by entering the required details""")

API_KEY = input("API_KEY: ")
API_HASH = input("API_HASH: ")

with TelegramClient(StringSession(), API_KEY, API_HASH) as client:
print("Here is your userbot srting, copy it to a safe place !!")
print("")
Expand Down
4 changes: 0 additions & 4 deletions userbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@

GOOGLE_CHROME_BIN = os.environ.get("GOOGLE_CHROME_BIN", None)

SCREENSHOT_LAYER_ACCESS_KEY = os.environ.get(
"SCREENSHOT_LAYER_ACCESS_KEY", None
)

OPEN_WEATHER_MAP_APPID = os.environ.get("OPEN_WEATHER_MAP_APPID", None)

WELCOME_MUTE = sb(os.environ.get(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,6 @@ async def welcome_mute(welcm):

CMD_HELP.update({
'welcome_mute': "If enabled in config.env or env var, \
this module will ban(or inform admins) the group join \
spammers if they match the userbot's algorithm of banning"
this module will ban(or inform admins of the group) when \
spammers join and match the userbot's banning algorithm."
})
2 changes: 1 addition & 1 deletion userbot/modules/gdrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ async def _(event):
if event.fwd_from:
return
folder_link = "https://drive.google.com/drive/u/2/folders/"+parent_id
await event.edit("Your current Google Drive upload directory: \n"+folder_link)
await event.edit(f"UserBot is currently uploading files to\n [This Folder]({folder_link})")


CMD_HELP.update({
Expand Down
71 changes: 36 additions & 35 deletions userbot/modules/screencapture.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,55 +6,56 @@
# The entire source code is OSSRPL except 'screencapture' which is MPL
# License: MPL and OSSRPL

""" Userbot module for ScreenshotLayer API """

import os
from requests import get

from userbot import SCREENSHOT_LAYER_ACCESS_KEY, CMD_HELP
import io
import traceback
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from userbot.events import register
from userbot import GOOGLE_CHROME_BIN, CHROME_DRIVER, CMD_HELP


@register(pattern=r".screencapture (.*)", outgoing=True)
async def capture(url):
""" For .screencapture command, capture a website and send the photo. """
if not url.text[0].isalpha() and url.text[0] not in ("/", "#", "@", "!"):
if SCREENSHOT_LAYER_ACCESS_KEY is None:
await url.edit(
"Need to get an API key from https://screenshotlayer.com/product \nModule stopping!"
)
if url.fwd_from:
return
await url.edit("Processing ...")
sample_url = "https://api.screenshotlayer.com/api/capture?access_key={}&\
url={}&fullpage={}&format={}&viewport={}"
input_str = url.pattern_match.group(1)
response_api = get(
sample_url.format(
SCREENSHOT_LAYER_ACCESS_KEY, input_str, "1", "PNG", "2560x1440"
),
stream=True,
)
content_type = response_api.headers["content-type"]
if "image" in content_type:
temp_file_name = "screencapture.png"
with open(temp_file_name, "wb") as file:
for chunk in response_api.iter_content(chunk_size=128):
file.write(chunk)
try:
try:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--test-type")
chrome_options.binary_location = GOOGLE_CHROME_BIN
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options)
input_str = url.pattern_match.group(1)
driver.get(input_str)
height = driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);")
width = driver.execute_script("return Math.max(document.body.scrollWidth, document.body.offsetWidth, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth);")
driver.set_window_size(width + 100, height + 100)
im_png = driver.get_screenshot_as_png()
# saves screenshot of entire page
driver.close()
message_id = url.message.id
if url.reply_to_msg_id:
message_id = url.reply_to_msg_id
with io.BytesIO(im_png) as out_file:
out_file.name = "screencapture.png"
await url.edit("Uploading screenshot as file..")
await url.client.send_file(
url.chat_id,
temp_file_name,
out_file,
caption=input_str,
force_document=True,
reply_to=url.message.reply_to_msg_id,
reply_to=message_id
)
await url.delete()
except BaseException:
await url.edit(response_api.text)
os.remove(temp_file_name)
else:
await url.edit(response_api.text)


except Exception:
await url.edit(traceback.format_exc())

CMD_HELP.update({
"screencapture": ".screencapture <url>\
\nUsage: Takes a screenshot of a website and sends the screenshot."
Expand Down
61 changes: 61 additions & 0 deletions userbot/modules/sql_helper/welcome_sql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
try:
from userbot.modules.sql_helper import SESSION, BASE
except ImportError:
raise AttributeError

from sqlalchemy import BigInteger, Boolean, Column, String, UnicodeText

class Welcome(BASE):
__tablename__ = "welcome"
chat_id = Column(String(14), primary_key=True)
custom_welcome_message = Column(UnicodeText, nullable=False)
media_file_id = Column(UnicodeText)
should_clean_welcome = Column(Boolean, default=False)
previous_welcome = Column(BigInteger)

def __init__(self, chat_id, custom_welcome_message, should_clean_welcome, previous_welcome, media_file_id=None):
self.chat_id = str(chat_id)
self.custom_welcome_message = custom_welcome_message
self.media_file_id = media_file_id
self.should_clean_welcome = should_clean_welcome
self.previous_welcome = previous_welcome


Welcome.__table__.create(checkfirst=True)


def get_current_welcome_settings(chat_id):
try:
return SESSION.query(Welcome).filter(Welcome.chat_id == str(chat_id)).one()
except:
return None
finally:
SESSION.close()


def add_welcome_setting(chat_id, custom_welcome_message, should_clean_welcome, previous_welcome,media_file_id=None):
try:
adder = Welcome(chat_id, custom_welcome_message, should_clean_welcome, previous_welcome, media_file_id)
SESSION.add(adder)
SESSION.commit()
return True
except:
return False


def rm_welcome_setting(chat_id):
try:
rem = SESSION.query(Welcome).get(str(chat_id))
if rem:
SESSION.delete(rem)
SESSION.commit()
return True
except:
return False


def update_previous_welcome(chat_id, previous_welcome):
row = SESSION.query(Welcome).get(chat_id)
row.previous_welcome = previous_welcome
# commit the changes to the DB
SESSION.commit()
8 changes: 6 additions & 2 deletions userbot/modules/stickers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ async def kang(args):
emojibypass = True
elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs')
in message.media.document.attributes):
photo = io.BytesIO()
await bot.download_file(message.media.document, photo)
emoji = message.media.document.attributes[0].alt
emojibypass = True
is_anim = True
photo = 1
else:
await args.edit("`Unsupported File!`")
return
Expand Down Expand Up @@ -84,6 +85,7 @@ async def kang(args):
file.name = "sticker.png"
image.save(file, "PNG")
else:
file.name = "sticker.tgs"
packname += "_anim"
packnick += " animated"
cmd = '/newanimated'
Expand All @@ -102,7 +104,9 @@ async def kang(args):
await conv.send_message(packname)
await conv.get_response()
if is_anim:
await bot.forward_messages('Stickers', [message.id], args.chat_id)
file.seek(0)
await conv.send_file(file, force_document=True)
# await bot.forward_messages('Stickers', [message.id], args.chat_id)
else:
file.seek(0)
await conv.send_file(file, force_document=True)
Expand Down
134 changes: 134 additions & 0 deletions userbot/modules/welcomes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
from telethon.utils import pack_bot_file_id
from userbot.modules.sql_helper.welcome_sql import get_current_welcome_settings, add_welcome_setting, rm_welcome_setting
from userbot.events import register
from userbot import CMD_HELP, bot, LOGS
from telethon.events import ChatAction


@bot.on(ChatAction)
async def welcome_to_chat(event):
cws = get_current_welcome_settings(event.chat_id)
if cws:
"""user_added=False,
user_joined=True,
user_left=False,
user_kicked=False,"""
if event.user_joined or event.user_added:
if cws.should_clean_welcome:
try:
await event.client.delete_messages(
event.chat_id,
cws.previous_welcome
)
except Exception as e:
LOGS.warn(str(e))

a_user = await event.get_user()
chat = await event.get_chat()
me = await event.client.get_me()

title = chat.title if chat.title else "this chat"

participants = await event.client.get_participants(chat)
count = len(participants)

current_saved_welcome_message = cws.custom_welcome_message

mention = "[{}](tg://user?id={})".format(a_user.first_name, a_user.id)
my_mention = "[{}](tg://user?id={})".format(me.first_name, me.id)

first = a_user.first_name
last = a_user.last_name
if last:
fullname = f"{first} {last}"
else:
fullname = first

username = f"@{a_user.username}" if a_user.username else mention

userid = a_user.id

my_first = me.first_name
my_last = me.last_name
if my_last:
my_fullname = f"{my_first} {my_last}"
else:
my_fullname = my_first

my_username = f"@{me.username}" if me.username else my_mention

current_message = await event.reply(
current_saved_welcome_message.format(mention=mention,
title=title,
count=count,
first=first,
last=last,
fullname=fullname,
username=username,
userid=userid,
my_first=my_first,
my_last=my_last,
my_fullname=my_fullname,
my_username=my_username,
my_mention=my_mention),
file=cws.media_file_id
)


@register(outgoing=True, pattern=r"^.welcome(?: |$)(.*)")
async def save_welcome(event):
if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
if event.fwd_from:
return
msg = await event.get_reply_message()
input_str = event.pattern_match.group(1)
if input_str:
if add_welcome_setting(event.chat_id, input_str, True, 0) is True:
await event.edit("`Welcome note saved !!`")
else:
await event.edit("`I can only have one welcome note per chat !!`")
elif msg and msg.media:
bot_api_file_id = pack_bot_file_id(msg.media)
if add_welcome_setting(event.chat_id, msg.message, True, 0, bot_api_file_id) is True:
await event.edit("`Welcome note saved !!`")
else:
await event.edit("`I can only have one welcome note per chat !!`")
elif msg.message is not None:
if add_welcome_setting(event.chat_id, msg.message, True, 0) is True:
await event.edit("`Welcome note saved !!`")
else:
await event.edit("`I can only have one welcome note per chat !!`")


@register(outgoing=True, pattern="^.show welcome$")
async def show_welcome(event):
if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
if event.fwd_from:
return
cws = get_current_welcome_settings(event.chat_id)
if cws:
await event.edit(f"`The current welcome message is:`\n{cws.custom_welcome_message}")
else:
await event.edit("`No welcome note saved here !!`")

@register(outgoing=True, pattern="^.del welcome")
async def del_welcome(event):
if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
if event.fwd_from:
return
if rm_welcome_setting(event.chat_id) is True:
await event.edit("`Welcome note deleted for this chat.`")
else:
await event.edit("`Do I even have a welcome note here ?`")


CMD_HELP.update({
"welcome": "\
.welcome <notedata/reply>\
\nUsage: Saves (or updates) notedata / replied message as a welcome note in the chat.\
\nAvailable variables for formatting welcome messages : {mention}, {title}, {count}, {first}, {last}, {fullname}, {userid}, {username}, {my_first}, {my_fullname}, {my_last}, {my_mention}, {my_username}\
\n\n.show welcome\
\nUsage: Gets your current welcome message in the chat.\
\n\n.del welcome\
\nUsage: Deletes the welcome note for the current chat.\
"})

0 comments on commit b475696

Please sign in to comment.