Store user profile pictures in bot database and show them in authorization panel

This commit is contained in:
Davte 2020-10-07 16:22:51 +02:00
parent 17b26ec23e
commit ddf25f8dd1
Signed by: Davte
GPG Key ID: 209AE674A0007425
4 changed files with 132 additions and 26 deletions

View File

@ -11,7 +11,7 @@ __author__ = "Davide Testa"
__email__ = "davide@davte.it" __email__ = "davide@davte.it"
__credits__ = ["Marco Origlia", "Nick Lee @Nickoala"] __credits__ = ["Marco Origlia", "Nick Lee @Nickoala"]
__license__ = "GNU General Public License v3.0" __license__ = "GNU General Public License v3.0"
__version__ = "2.6.17" __version__ = "2.6.18"
__maintainer__ = "Davide Testa" __maintainer__ = "Davide Testa"
__contact__ = "t.me/davte" __contact__ = "t.me/davte"

View File

@ -315,6 +315,7 @@ def get_authorization_function(bot: Bot):
async def _authorization_command(bot: Bot, async def _authorization_command(bot: Bot,
update: dict, update: dict,
user_record: OrderedDict, user_record: OrderedDict,
language: str,
mode: str = 'auth'): mode: str = 'auth'):
db = bot.db db = bot.db
text = get_cleaned_text(bot=bot, update=update, replace=[mode]) text = get_cleaned_text(bot=bot, update=update, replace=[mode])
@ -407,6 +408,17 @@ async def _authorization_command(bot: Bot,
user_record=user_record, user_record=user_record,
admin_record=admin_record admin_record=admin_record
) )
if bot.db['user_profile_photos'].find_one(user_id=user_record['id']):
buttons.append(
make_button(
text=bot.get_message('authorization', 'auth_button',
'profile_picture_button',
language=language),
prefix='auth:///',
delimiter='|',
data=['picture', user_record['id']]
)
)
reply_markup = make_inline_keyboard(buttons, 1) reply_markup = make_inline_keyboard(buttons, 1)
return dict( return dict(
text=result, text=result,
@ -418,6 +430,7 @@ async def _authorization_command(bot: Bot,
async def _authorization_button(bot: Bot, async def _authorization_button(bot: Bot,
update: dict, update: dict,
user_record: OrderedDict, user_record: OrderedDict,
language: str,
data: Union[str, List[Union[int, str]]]): data: Union[str, List[Union[int, str]]]):
if len(data) == 0: if len(data) == 0:
data = [''] data = ['']
@ -435,6 +448,17 @@ async def _authorization_button(bot: Bot,
user_record=other_user_record, user_record=other_user_record,
admin_record=user_record admin_record=user_record
) )
if bot.db['user_profile_photos'].find_one(user_id=other_user_record['id']):
buttons.append(
make_button(
text=bot.get_message('authorization', 'auth_button',
'profile_picture_button',
language=language),
prefix='auth:///',
delimiter='|',
data=['picture', user_record['id']]
)
)
reply_markup = make_inline_keyboard(buttons, 1) reply_markup = make_inline_keyboard(buttons, 1)
elif command in ['set'] and len(arguments) > 1: elif command in ['set'] and len(arguments) > 1:
other_user_id, new_privileges, *_ = arguments other_user_id, new_privileges, *_ = arguments
@ -507,7 +531,41 @@ async def _authorization_button(bot: Bot,
user_record=other_user_record, user_record=other_user_record,
admin_record=user_record admin_record=user_record
) )
if bot.db['user_profile_photos'].find_one(user_id=other_user_record['id']):
buttons.append(
make_button(
text=bot.get_message('authorization', 'auth_button',
'profile_picture_button',
language=language),
prefix='auth:///',
delimiter='|',
data=['picture', user_record['id']]
)
)
reply_markup = make_inline_keyboard(buttons, 1) reply_markup = make_inline_keyboard(buttons, 1)
elif command in ['picture'] and len(arguments) > 0:
photo_record = bot.db['user_profile_photos'].find_one(
user_id=arguments[0],
order_by=['-update_datetime'],
)
other_user_record = bot.db['users'].find_one(id=arguments[0])
if photo_record is None:
result = bot.get_message('admin', 'error', 'text',
language=language)
else:
caption, buttons = bot.Role.get_user_role_text_and_buttons(
user_record=other_user_record,
admin_record=user_record
)
await bot.sendPhoto(
chat_id=user_record['telegram_id'],
photo=photo_record['telegram_file_id'],
caption=caption,
reply_markup=make_inline_keyboard(
buttons=buttons
),
parse_mode='HTML'
)
if text: if text:
return dict( return dict(
text=result, text=result,
@ -570,18 +628,24 @@ def init(telegram_bot: Bot,
authorization_messages['auth_command']['description'] authorization_messages['auth_command']['description']
), ),
authorization_level='moderator') authorization_level='moderator')
async def authorization_command(bot, update, user_record): async def authorization_command(bot, update, user_record, language):
return await _authorization_command(bot, update, user_record) return await _authorization_command(bot=bot, update=update,
user_record=user_record,
language=language)
@telegram_bot.button('auth:///', @telegram_bot.button('auth:///',
description=authorization_messages['auth_button']['description'], description=authorization_messages['auth_button']['description'],
separator='|', separator='|',
authorization_level='moderator') authorization_level='moderator')
async def authorization_button(bot, update, user_record, data): async def authorization_button(bot, update, user_record, language, data):
return await _authorization_button(bot, update, user_record, data) return await _authorization_button(bot=bot, update=update,
user_record=user_record,
language=language, data=data)
@telegram_bot.command('/ban', aliases=[], show_in_keyboard=False, @telegram_bot.command('/ban', aliases=[], show_in_keyboard=False,
description=authorization_messages['ban_command']['description'], description=authorization_messages['ban_command']['description'],
authorization_level='moderator') authorization_level='moderator')
async def ban_command(bot, update, user_record): async def ban_command(bot, update, user_record, language):
return await _authorization_command(bot, update, user_record, mode='ban') return await _authorization_command(bot=bot, update=update,
user_record=user_record,
language=language, mode='ban')

View File

@ -3162,18 +3162,25 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
""" """
while 1: while 1:
await asyncio.sleep(interval) await asyncio.sleep(interval)
users_profile_pictures_to_update = OrderedDict()
now = datetime.datetime.now()
# Iterate through a copy since asyncio.sleep(0) is awaited at each # Iterate through a copy since asyncio.sleep(0) is awaited at each
# cycle iteration. # cycle iteration.
for telegram_id, user in self.recent_users.copy().items(): for telegram_id, user in self.recent_users.copy().items():
new_record = dict() new_record = dict()
with self.db as db: with self.db as db:
user_record = db['users'].find_one(telegram_id=telegram_id) user_record = db['users'].find_one(telegram_id=telegram_id)
for key in [ user_picture_record = db['user_profile_photos'].find_one(
'first_name', user_id=user_record['id'],
'last_name', order_by=['-update_datetime']
'username', )
'language_code' # If user profile picture needs to be updated, add it to the OD
]: if (user_picture_record is None
or user_picture_record['update_datetime']
< now - datetime.timedelta(days=1)):
users_profile_pictures_to_update[telegram_id] = user_picture_record
for key in ('first_name', 'last_name',
'username', 'language_code', ):
new_record[key] = (user[key] if key in user else None) new_record[key] = (user[key] if key in user else None)
if ( if (
( (
@ -3206,6 +3213,37 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
if telegram_id in self.recent_users: if telegram_id in self.recent_users:
del self.recent_users[telegram_id] del self.recent_users[telegram_id]
await asyncio.sleep(0) await asyncio.sleep(0)
# Update user profile pictures
for telegram_id, user_picture_record in users_profile_pictures_to_update.items():
try:
user_profile_photos = await self.getUserProfilePhotos(
user_id=telegram_id,
offset=0,
limit=1
)
if (user_profile_photos is not None
and 'photos' in user_profile_photos
and len(user_profile_photos['photos'])):
current_photo = user_profile_photos['photos'][0][0]
if (user_picture_record is None
or current_photo['file_id']
!= user_picture_record['telegram_file_id']):
db['user_profile_photos'].insert(dict(
user_id=user_record['id'],
telegram_file_id=current_photo['file_id'],
update_datetime=now
))
else:
db['user_profile_photos'].upsert(
dict(
user_id=user_record['id'],
telegram_file_id=current_photo['file_id'],
update_datetime=now
),
['user_id', 'telegram_file_id']
)
except Exception as e:
logging.error(e)
def get_user_record(self, update): def get_user_record(self, update):
"""Get user_record of update sender. """Get user_record of update sender.

View File

@ -709,17 +709,25 @@ default_authorization_messages = {
} }
}, },
'auth_button': { 'auth_button': {
'description': { 'appointed': {
'en': "Edit user permissions", 'en': "Permission granted",
'it': "Cambia il grado di autorizzazione di un utente" 'it': "Permesso conferito"
},
'back_to_user': {
'en': "Back to user",
'it': "Torna all'utente"
}, },
'confirm': { 'confirm': {
'en': "Are you sure?", 'en': "Are you sure?",
'it': "Sicuro sicuro?" 'it': "Sicuro sicuro?"
}, },
'back_to_user': { 'description': {
'en': "Back to user", 'en': "Edit user permissions",
'it': "Torna all'utente" 'it': "Cambia il grado di autorizzazione di un utente"
},
'no_change': {
'en': "No change suggested!",
'it': "È già così!"
}, },
'permission_denied': { 'permission_denied': {
'user': { 'user': {
@ -732,14 +740,10 @@ default_authorization_messages = {
'it': "Non hai l'autorità di conferire questo permesso!" 'it': "Non hai l'autorità di conferire questo permesso!"
} }
}, },
'no_change': { 'profile_picture_button': {
'en': "No change suggested!", 'en': "🖼 Profile picture",
'it': "È già così!" 'it': "🖼 Foto profilo",
}, },
'appointed': {
'en': "Permission granted",
'it': "Permesso conferito"
}
}, },
} }