I am new in python, I created telegram bot with python 3.
to show product from db I write code like that ,
cart: Dict[List[db.Product, int]] = {}
for product in products:
if product.price is None:
continue
message = product.send_as_message(self.chat.id)
cart[message['result']['message_id']] = [product, 0]
inline_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(strings.menu_add_to_cart,
callback_data="cart_add")]])
if product.image is None:
self.bot.edit_message_text(chat_id=self.chat.id,
message_id=message['result']['message_id'],
text=product.text(),
reply_markup=inline_keyboard)
else:
self.bot.edit_message_caption(chat_id=self.chat.id,
message_id=message['result']['message_id'],
caption=product.text(),
reply_markup=inline_keyboard)
problem is when I want remove this product , I can't remove image of product , I used cart.clear() but it doesnt work?
I found solution how to remove item from dict "del my_dict['key'] ". I my case I deleted message which show my product
self.bot.delete_message(chat_id=self.chat.id,
message_id=temp_msg,
caption=' ',
reply_markup=None)
Related
This code:
usr = await app.resolve_peer(uid)
udata = InputUser(user_id=usr.user_id, access_hash=usr.access_hash)
r = await app.invoke(functions.messages.DeleteChatUser(chat_id=chan, user_id=udata))
print(r)
Returns:
AttributeError: 'InputPeerChannel' object has no attribute 'to_bytes'
In docs:
class pyrogram.raw.functions.messages.DeleteChatUser**
Deletes a user from a chat and sends a service message on it.
Parameters:
chat_id (int 64-bit) – Chat ID.
user_id (InputUser) – User ID to be deleted.
revoke_history (bool, optional) – Remove the entire chat history of the specified user in this chat.
What`s wrong?
Maybe my udata in the wrong type?
I'm not sure, but "DeleteChatUser" it seems to only work for groups, not channels.
For groups maybe working code:
cid = -10083757838484 # Example group_id
usr = await app.resolve_peer(uid)
if cid < 0:
cid = cid * (-1) # Removing a minus from group_id
udata = InputUser(user_id=usr.user_id, access_hash=usr.access_hash)
r = await app.invoke(functions.messages.DeleteChatUser(chat_id=cid, user_id=udata))
print(r)
But I needed a solution for the channel, so I used:
r = await app.ban_chat_member(int(cid), int(usr))
I have made a telegram member scraper and inviter with Python. It was successful on some tests, but there are times my accounts get banned with upon seeing this error message:
AttributeError: 'ChatForbidden' object has no attribute 'access_hash'
I'm not sure why would it show ChatForbidden if I am already an admin of a group. It's hard to test these as I had to buy new phone numbers every time.
Here's a sample and explanation of my code to invite members to a group:
# Log in into the telegram account
client = TelegramClient('Tg_scraper', api_id, api_hash)
chats = []
last_date = None
chunk_size = 200
groups = []
hash_list = []
# Get all the groups/channel of the account
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash=0
))
chats.extend(result.chats)
# Puts all the group/channel into a list
i = 0
print('Enter a NUMBER to choose a group where the members will be invited into:')
for chat in chats:
try:
groups.append(chat)
hash_list.append(chat.access_hash)
print(f"({i})" + ' - ' + chat.title)
i += 1
except:
continue
g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]
target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)
Upon the last line, target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash) is where I encounter the error I have stated above. Upon receiving that error, I get banned.
Does this have something to do with permissions? Do new accounts get banned for botting? It works on my first few tests, but then now I can't invite. Thank you so much for anyone who could help in advance.
I am already an admin of a group
This error is unrelated to your permission level.
Upon the last line is where I encounter the error
Wrong. you encounter this error because you're not coding it right with types in mind, expecting all your .chats are groups. Telegram doesn't tell you what fields exactly have, as you see in this error.
You must use type checking to limit your chats objects to only what you expect, your try block is appending then erroring, so, rather than a plain:
except:
continue
you need to actually confirm it won't error when accessing fields.
print('Enter a NUMBER to choose a group where the members will be invited into:')
i = 0
for chat in chats:
if isinstance(chat, telethon.types.Channel):
if chat.broadcast: continue # ignore non-group
groups.append(chat)
hash_list.append(chat.access_hash)
print(f"({i})" + ' - ' + chat.title)
i += 1
g_index = input("Enter a Number: ")
target_group = groups[int(g_index)]
In telegram when I click Subscribers it shows me about 50 last users and about 150-200 deleted users.
I tried this:
async for user in client.iter_participants(chat_id):
if user.deleted:
print(user)
This gives me only last 50 users and 6-8 deleted users. I need all 150-200 deleted users. How can I get them?
I solved this problem using GetParticipantsRequest with offset parameter somehow like this:
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
chat_id = -123456
offset = 0
while True:
participants = await client(GetParticipantsRequest(
channel=chat_id,
filter=ChannelParticipantsSearch(''),
offset=offset,
limit=10000,
hash=0
))
deleted_users = []
for user in participants:
if user.deleted:
deleted_users.append(user)
if not deleted_users:
break
# doings with deleted_users
Not sure about iter_participants, but get_participants works in my case.
channel_id = -1234567890 # TODO: add channel id
users = client.get_participants(client.get_input_entity(channel_id))
for user in users:
if user.deleted:
print(user)
I am brand new to odoo! On odoo 13 EE I am trying to create and confirm a vendor bill after importing a purchase order and the item receipts. I can create an invoice directly, but haven't been able to link that to the PO/receipt?
Sadly under purchase.order the method action_create_invoice seems hidden from the API
order_id = PurchaseOrder.create(po)
purchaseorder = PurchaseOrder.browse([order_id])
print("Before validating:", purchaseorder.name, purchaseorder.state) # draft
odoo.env.context['check_move_validity'] = True
purchaseorder.button_confirm()
purchaseorder = PurchaseOrder.browse([order_id])
picking_count = purchaseorder.picking_count
print("After Post:", purchaseorder.name, purchaseorder.state, "picking_count = ", purchaseorder.picking_count)
if picking_count == 0:
print("Nothing to receive. Straight to to Billing.") # ok so far
tryme = purchaseorder.action_view_invoice()
## Error => odoorpc.error.RPCError: type object 'purchase.order' has no attribute 'action_create_invoice'
SO I tried overriding/extending this way
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
#api.model
def create_invoice(self, context=None):
# try 1 => odoorpc.error.RPCError: 'super' object has no attribute # 'action_create_invoice'
rtn = super().action_create_invoice(self)
# try2 => odoorpc.error.RPCError: name 'action_create_invoice' is # not defined
# rtn = action_create_invoice(self)
# try3 => Error %s 'super' object has no attribute ' # action_create_invoice'
# rtn = super(models.Model, self).action_create_invoice(self)
return rtn
I hope somebody can suggest a solution! Thank you.
Please dont customize it without having a functional knowledge in odoo. In odoo, if you go to purchase settings, you can find billing options under invoicing where you can find 2 options, ordered quantity and received quantity. if it is ordered quantity, then you can create invoice after confirming the Purchase order. if it is received quantity, then after confirming the purchase order, a incoming shipment will be created and after the incoming shipment is processed, you can find the create invoice button in purchase order
If you can do it from the browser client, than you should just look what API commands the browser sends to the odoo server (in Chrome by enabling the debug view by pressing F12, and looking in the network tab), so that you just need to copy that communication.
I tried to use the telethon to develop a telegram bot, when I used AddChatUserRequest to add a user to a group
client(AddChatUserRequest(1168070860, user.id, fwd_limit=10))
I met the error:
telethon.errors.rpcerrorlist.ChatIdInvalidError: Invalid object ID for
a chat. Make sure to pass the right types, for instance making sure
that the request is designed for chats (not channels/megagroups) or
otherwise look for a different one more suited\nAn example working
with a megagroup and AddChatUserRequest, it will fail because
megagroups are channels. Use InviteToChannelRequest instead (caused by
AddChatUserRequest)
I used these code to get the group's information:
chats = client(GetDialogsRequest(
offset_date=None,
offset_id=0,
offset_peer=InputPeerEmpty(),
limit=200,
hash = 0
)).chats
groups = []
for chat in chats:
try:
if chat.megagroup == True:
groups.append(chat)
print(chat.title,chat.id)
except:
continue
And here's the group's information that I tried to add user:
Channel(left=False, id=1168070860, banned_rights=None, title='ruby and his friends', version=0, verified=False, signatures=False, broadcast=False, participants_count=None, creator=True, has_geo=False, photo=ChatPhoto(dc_id=1, photo_small=FileLocationToBeDeprecated(local_id=270793, volume_id=806122192), photo_big=FileLocationToBeDeprecated(local_id=270795, volume_id=806122192)), username='lanlugroup', megagroup=True, restricted=False, default_banned_rights=ChatBannedRights(change_info=True, until_date=datetime.datetime(2038, 1, 19, 3, 14, 7, tzinfo=datetime.timezone.utc), send_inline=False, invite_users=False, pin_messages=True, send_media=False, send_gifs=False, send_games=False, embed_links=False, send_stickers=False, send_messages=False, view_messages=False, send_polls=False), restriction_reason=None, min=False, has_link=False, scam=False, date=datetime.datetime(2019, 4, 1, 12, 44, 47, tzinfo=datetime.timezone.utc), admin_rights=None, access_hash=-5901560198799322202)
I used the id 1168070860 as the chat_id in AddChatUserRequest
(BTW, I login with the phone number as a normal user, not as a bot)
Use InviteToChannelRequest instead. My solution:
chat_id = "mychatid"
users = ['UserName']
response = client.invoke(ResolveUsernameRequest(chat_id))
target_group_entity = InputPeerChannel(response.chats[0].id, response.chats[0].access_hash)
try:
res = client(InviteToChannelRequest(channel=target_group_entity, users=users ))
except Exception as e:
print("spam protection: " + e.message + ": " + str(e))