Skip to content

Commit

Permalink
implement mega to upload large file
Browse files Browse the repository at this point in the history
  • Loading branch information
Koushikphy committed Jul 23, 2022
1 parent c6f9c69 commit 0a98c15
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 30 deletions.
4 changes: 4 additions & 0 deletions .env_sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
TOKEN=<bot token>
ALLOWED_USERS=<user1 telegram ID> <user2> <user3>
ADMIN=<admin telegram ID>
MEGA=<mega_username>,<mega_password>,<mega_folder to upload to>
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ name = "pypi"

[packages]
pytelegrambotapi = "*"
"mega.py" = "*"

[dev-packages]

Expand Down
68 changes: 67 additions & 1 deletion Pipfile.lock

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

3 changes: 2 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ Take Photo/Audio/Video from webcam by remotely controlling it using a Telegram b
1. `/photo` - Take photo
2. `/audio` - Take audio
3. `/video` - Take video

1. A mega account is also needed to upload larger files and accordingly the mega account credentials need to be put in the .env file.

**NOTE:**

1. If different devices are used for video and audio recording, then there may be some sync issue.
1. Current codebase uses a polling method for the bot to communicate with the telegram server, for a production level solution a webhook should be used.
1. A smaple `.env` file is also provided [env_sample](./.env_sample)

<!-- cut video with ffmpeg -->
<!-- ffmpeg -ss 00:01:00 -to 00:02:00 -i input.mp4 -c copy output.mp4 -->
66 changes: 39 additions & 27 deletions telegramBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@
from telebot import TeleBot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
import logging, shutil
from mega import Mega






TOKEN = os.getenv('TOKEN')
ALLOWED_USERS = [int(i) for i in os.getenv('ALLOWED_USERS').split()]
ADMIN = os.getenv('ADMIN')



bot = TeleBot(TOKEN, parse_mode='HTML')


Expand All @@ -25,7 +33,7 @@ def remind(self, userid: int):

def nudge(self):
message = bot.send_message(self.userid, "Recording in progress. Don't forget to finish")
deleteMessage(message,10) # delete this notification after 10 seconds
deleteMessage(message,60) # delete this notification after 10 seconds

def cancel(self):
self.timer.cancel()
Expand Down Expand Up @@ -73,15 +81,15 @@ def checkRequest(message):



@bot.message_handler(commands='start')
@bot.message_handler(commands=['start'])
def send_welcome(message):
if checkRequest(message):
return
bot.send_message(message.from_user.id, "Welcome to the spy bot")



@bot.message_handler(commands='photo')
@bot.message_handler(commands=['photo'])
def send_photo(message):
user = message.from_user.id
if checkRequest(message):
Expand Down Expand Up @@ -143,7 +151,7 @@ def keepPhoto(self,ranStr):
photoK = PhotoKeeper()


@bot.message_handler(commands='audio')
@bot.message_handler(commands=['audio'])
def send_audio(message):
# start audio recording
user = message.from_user.id
Expand All @@ -159,7 +167,7 @@ def send_audio(message):



@bot.message_handler(commands='video')
@bot.message_handler(commands=['video'])
def send_video(message):
user = message.from_user.id
if checkRequest(message):
Expand Down Expand Up @@ -196,7 +204,7 @@ def callback_query(call):
remind.cancel() # clear all reminder
user = call.from_user.id

if not recorder.isRunning :
if not recorder.isRunning:
bot.send_message(user, "No recording is currently in progress !!!")
return

Expand All @@ -205,27 +213,28 @@ def callback_query(call):
size = os.path.getsize(file)/1e6

logger.info(f"Recording finished: {os.path.basename(file)} ({act:.2f} sec) ({size:.2f} MB)")
msg = bot.send_message(user,
"Recording saved successfully. Wait while the bot uploads the file." +
(" Due Telegram restrictions the file will be split." if size>48.0 else "")
)
if size > 48.0: # Telegram file size restriction is 50 MB
files = splitFilesInChunks(file)
else:
files = [file]

try:
for file in files:
print('-----------------', os.path.getsize(file))
with open(file, 'rb') as f:
if file.endswith('mp4'):
bot.send_video(user, f)
else:
bot.send_audio(user, f)
msg = bot.send_message(user, "Recording saved successfully. Wait while the bot uploads the file.")

uploaded = False

try: # telegram server won't accept file larger than 50 mb
if size>49:
raise Exception('File too large to upload')
with open(file,'rb') as ff:
if file.endswith('mp4'):
bot.send_video(user, ff)
else:
bot.send_audio(user, ff)
except:
bot.send_message(user,
f"Something went wrong while uploading the file file. You can find the file stored as {file}")

mm = bot.send_message(user, f"Something went wrong while uploading the file to telegram server."
"The bot will upload the file to a remote server")
link = mClient.get_upload_link(mClient.upload(file, MEGA_FOLDER))
deleteMessage(mm)
bot.send_message(user,link)
uploaded = True
finally:
if not uploaded: # upload it anyway for future storage
mClient.upload(file, MEGA_FOLDER)

deleteMessage(msg)

Expand All @@ -240,4 +249,7 @@ def callback_query(call):


bot.send_message(ADMIN, "Starting bot")
bot.infinity_polling()
mega = Mega()
user,pasw,MEGA_FOLDER = os.getenv('MEGA').split(',')
mClient = mega.login(user,pasw)
bot.infinity_polling()
2 changes: 1 addition & 1 deletion utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class AVRecorder:

def __init__(self):
self.commonFlags = 'ffmpeg -hide_banner -f dshow -y -video_size 1280x720 -rtbufsize 2G'.split()
self.vidFlags = "-vcodec libx265 -crf 28 -r 21".split()
self.vidFlags = "-vcodec libx265 -crf 28 -r 17".split()
# get list of devices with `ffmpeg -list_devices true -f dshow -i dummy`
# self.audioInput = "audio=Headset (realme Buds Wireless 2 Neo Hands-Free AG Audio)"
# self.videoInput = "video=HP HD Camera"
Expand Down

0 comments on commit 0a98c15

Please sign in to comment.