Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahesh0253 committed Sep 13, 2020
0 parents commit 0b0be7b
Show file tree
Hide file tree
Showing 12 changed files with 597 additions and 0 deletions.
144 changes: 144 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Personal files
*.session
*.session-journal
.vscode
*test.py

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
## [Media Search bot](https://github.com/Mahesh0253/Media-Search-bot)

* Index channel files for inline search.
* When you going to post file on telegram channel this bot will save that in database, So you and your subscribers can easily search that in inline mode.
* This bot supports document, video and audio file formats with caption.

### Installation

#### Easy Way
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

#### Hard Way

```sh
python3 -m venv env
. ./env/bin/activate
pip install -r requirements.txt
# <Create config.py with variables as given below>
python bot.py
```
Check `sample_info.py` before editing `info.py` file

#### Variables

##### Required Variables
* `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token.

* `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps)
* `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps)
* `CHANNELS`: Username or id of channel. Separate multiple channels by space
* `ADMINS`: Username or id of Admin. Separate multiple Admins by space
* `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/VQnmcBnguPY)
* `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/VQnmcBnguPY)

##### Optional Variable
* `COLLECTION_NAME`: Name of the collections. Defaults to Telegram_files. If you going to use same database, then use different collection name for each bot

### How to use?
* First add this bot in channel as a Admin
* Then whenever you post file, bot will save that in database, So you can easily search whenever you want.

### Admin commands
```
channel - Get basic infomation about channels
total - Show total of saved files
logger - Get log file
```
### Contributions
Contributions are welcome.

### Thanks to [Pyrogram](https://github.com/pyrogram/pyrogram)

### License
Code released under [The GNU General Public License](LICENSE).
64 changes: 64 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"name": "Media Search bot",
"description": "When you going to post file on telegram channel this bot will save that in database, So you can easily search that in inline mode",
"keywords": [
"telegram",
"best",
"indian",
"pyrogram",
"media",
"search",
"channel",
"index",
"inline"
],
"website": "https://github.com/Mahesh0253/Media-Search-bot",
"repository": "https://github.com/Mahesh0253/Media-Search-bot",
"env": {
"BOT_TOKEN": {
"description": "Your bot token.",
"value": ""
},
"API_ID": {
"description": "Get this value from https://my.telegram.org",
"value": ""
},
"API_HASH": {
"description": "Get this value from https://my.telegram.org",
"value": ""
},
"CHANNELS": {
"description": "Username or id of channel. Separate multiple channels by space.",
"value": ""
},
"ADMINS": {
"description": "Username or id of Admin. Separate multiple Admins by space.",
"value": ""
},
"DATABASE_URI": {
"description": "mongoDB URI. Get this value from https://www.mongodb.com. For more help watch this video - https://youtu.be/VQnmcBnguPY",
"value": ""
},
"DATABASE_NAME": {
"description": "Name of the database in mongoDB. For more help watch this video - https://youtu.be/VQnmcBnguPY",
"value": ""
},
"COLLECTION_NAME": {
"description": "Name of the collections. Defaults to Telegram_files. If you going to use same database, then use different collection name for each bot",
"value": "Telegram_files",
"required": false
}
},
"addons": [],
"buildpacks": [
{
"url": "heroku/python"
}
],
"formation": {
"worker": {
"quantity": 1,
"size": "free"
}
}
}
40 changes: 40 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import logging
import logging.config

# Get logging configurations
logging.config.fileConfig('logging.conf')
logging.getLogger().setLevel(logging.ERROR)

from pyrogram import Client, __version__
from pyrogram.raw.all import layer
from utils import Media
from info import SESSION, API_ID, API_HASH, BOT_TOKEN


class Bot(Client):

def __init__(self):
super().__init__(
session_name=SESSION,
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN,
workers=150,
plugins={"root": "plugins"},
sleep_threshold=10,
)

async def start(self):
await super().start()
await Media.ensure_indexes()
me = await self.get_me()
self.username = '@' + me.username
print(f"{me.first_name} with for Pyrogram v{__version__} (Layer {layer}) started on {me.username}.")

async def stop(self, *args):
await super().stop()
print("Bot stopped. Bye.")


app = Bot()
app.run()
26 changes: 26 additions & 0 deletions info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import re
from os import environ

# Bot information
SESSION = environ.get('SESSION', 'Media_search')
API_ID = environ['API_ID']
API_HASH = environ['API_HASH']
BOT_TOKEN = environ['BOT_TOKEN']

# Admins & Channels
ADMINS = [int(admin) if re.search('^\d+$', admin) else admin for admin in environ['ADMINS'].split()]
CHANNELS = [int(channel) if re.search('^-100\d+$', channel) else channel for channel in environ['CHANNELS'].split()]

# MongoDB information
DATABASE_URI = ['DATABASE_URI']
DATABASE_NAME = ['DATABASE_NAME']
COLLECTION_NAME = environ.get('COLLECTION_NAME', 'Telegram_files')

# Messages
START_MSG = """
**Hi, I'm Media Search bot**
Here you can search files in inline mode. Just press follwing buttons and start searching.
"""

SHARE_BUTTON_TEXT = 'Checkout {username} for searching files'
32 changes: 32 additions & 0 deletions logging.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=consoleFormatter,fileFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=consoleFormatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=ERROR
formatter=fileFormatter
args=('TelegramBot.log','w',)

[formatter_consoleFormatter]
format=%(asctime)s - %(lineno)d - %(name)s - %(module)s - %(levelname)s - %(message)s
datefmt=%I:%M:%S %p

[formatter_fileFormatter]
format=[%(asctime)s:%(name)s:%(lineno)d:%(levelname)s] %(message)s
datefmt=%m/%d/%Y %I:%M:%S %p
20 changes: 20 additions & 0 deletions plugins/channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from pyrogram import Client, filters
from utils import save_file
from info import CHANNELS

media_filter = filters.document | filters.video | filters.audio


@Client.on_message(filters.chat(CHANNELS) & media_filter)
async def media(bot, message):
"""Media Handler"""
for kind in ("document", "video", "audio"):
media = getattr(message, kind, None)
if media is not None:
break
else:
return

media.file_type = kind
media.caption = message.caption
await save_file(media)
Loading

0 comments on commit 0b0be7b

Please sign in to comment.