id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,400 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/test/test3_admin.py
|
test3_admin.AdminBot
|
class AdminBot(amanobot.Bot):
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if 'edit_date' not in msg:
self.sendMessage(chat_id, 'Edit the message, please.')
else:
self.sendMessage(chat_id, 'Add me to a group, please.')
# Make a router to route `new_chat_member` and `left_chat_member`
r = amanobot.helper.Router(by_content_type(), make_content_type_routing_table(self))
# Replace current handler with that router
self._router.routing_table['chat'] = r.route
def on_new_chat_member(self, msg, new_chat_member):
print('New chat member:', new_chat_member)
content_type, chat_type, chat_id = amanobot.glance(msg)
r = self.getChat(chat_id)
print(r)
r = self.getChatAdministrators(chat_id)
print(r)
print(amanobot.namedtuple.ChatMemberArray(r))
r = self.getChatMembersCount(chat_id)
print(r)
while 1:
try:
self.setChatTitle(chat_id, 'AdminBot Title')
print('Set title successfully.')
break
except NotEnoughRightsError:
print('No right to set title. Try again in 10 seconds ...')
time.sleep(10)
while 1:
try:
self.setChatPhoto(chat_id, open('gandhi.png', 'rb'))
print('Set photo successfully.')
time.sleep(2) # let tester see photo briefly
break
except NotEnoughRightsError:
print('No right to set photo. Try again in 10 seconds ...')
time.sleep(10)
while 1:
try:
self.deleteChatPhoto(chat_id)
print('Delete photo successfully.')
break
except NotEnoughRightsError:
print('No right to delete photo. Try again in 10 seconds ...')
time.sleep(10)
print('I am done. Remove me from the group.')
@staticmethod
def on_left_chat_member(msg, left_chat_member):
print('I see that I have left.')
|
class AdminBot(amanobot.Bot):
def on_chat_message(self, msg):
pass
def on_new_chat_member(self, msg, new_chat_member):
pass
@staticmethod
def on_left_chat_member(msg, left_chat_member):
pass
| 5 | 0 | 19 | 3 | 15 | 1 | 3 | 0.06 | 1 | 2 | 2 | 0 | 2 | 0 | 3 | 89 | 62 | 12 | 48 | 9 | 43 | 3 | 46 | 8 | 42 | 7 | 2 | 2 | 10 |
4,401 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/quiza.py
|
quiza.Quizzer
|
class Quizzer(amanobot.aio.helper.CallbackQueryOriginHandler):
def __init__(self, *args, **kwargs):
super(Quizzer, self).__init__(*args, **kwargs)
self._score = {True: 0, False: 0}
self._answer = None
async def _show_next_question(self):
x = random.randint(1,50)
y = random.randint(1,50)
sign, op = random.choice([('+', lambda a,b: a+b),
('-', lambda a,b: a-b),
('x', lambda a,b: a*b)])
answer = op(x,y)
question = '%d %s %d = ?' % (x, sign, y)
choices = sorted(list(map(random.randint, [-49]*4, [2500]*4)) + [answer])
await self.editor.editMessageText(question,
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))
]
)
)
return answer
async def on_callback_query(self, msg):
query_id, from_id, query_data = glance(msg, flavor='callback_query')
if query_data != 'start':
self._score[self._answer == int(query_data)] += 1
self._answer = await self._show_next_question()
async def on__idle(self, event):
text = '%d out of %d' % (self._score[True], self._score[True]+self._score[False])
await self.editor.editMessageText(
text + '\n\nThis message will disappear in 5 seconds to test deleteMessage',
reply_markup=None)
await asyncio.sleep(5)
await self.editor.deleteMessage()
self.close()
|
class Quizzer(amanobot.aio.helper.CallbackQueryOriginHandler):
def __init__(self, *args, **kwargs):
pass
async def _show_next_question(self):
pass
async def on_callback_query(self, msg):
pass
async def on__idle(self, event):
pass
| 5 | 0 | 10 | 1 | 9 | 0 | 1 | 0 | 1 | 5 | 0 | 0 | 4 | 2 | 4 | 20 | 42 | 7 | 35 | 15 | 30 | 0 | 25 | 15 | 20 | 2 | 3 | 1 | 5 |
4,402 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/quiza.py
|
quiza.QuizStarter
|
class QuizStarter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(QuizStarter, self).__init__(*args, **kwargs)
async def on_chat_message(self, msg):
content_type, chat_type, chat_id = glance(msg)
await self.sender.sendMessage(
'Press START to do some math ...',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[
InlineKeyboardButton(text='START', callback_data='start'),
]]
)
)
self.close()
|
class QuizStarter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
async def on_chat_message(self, msg):
pass
| 3 | 0 | 7 | 0 | 7 | 1 | 1 | 0.07 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 19 | 15 | 1 | 14 | 4 | 11 | 1 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
4,403 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/quiz.py
|
quiz.Quizzer
|
class Quizzer(amanobot.helper.CallbackQueryOriginHandler):
def __init__(self, *args, **kwargs):
super(Quizzer, self).__init__(*args, **kwargs)
self._score = {True: 0, False: 0}
self._answer = None
def _show_next_question(self):
x = random.randint(1,50)
y = random.randint(1,50)
sign, op = random.choice([('+', lambda a,b: a+b),
('-', lambda a,b: a-b),
('x', lambda a,b: a*b)])
answer = op(x,y)
question = '%d %s %d = ?' % (x, sign, y)
choices = sorted(list(map(random.randint, [-49]*4, [2500]*4)) + [answer])
self.editor.editMessageText(question,
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[
list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))
]
)
)
return answer
def on_callback_query(self, msg):
query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')
if query_data != 'start':
self._score[self._answer == int(query_data)] += 1
self._answer = self._show_next_question()
def on__idle(self, event):
text = '%d out of %d' % (self._score[True], self._score[True]+self._score[False])
self.editor.editMessageText(
text + '\n\nThis message will disappear in 5 seconds to test deleteMessage',
reply_markup=None)
time.sleep(5)
self.editor.deleteMessage()
self.close()
|
class Quizzer(amanobot.helper.CallbackQueryOriginHandler):
def __init__(self, *args, **kwargs):
pass
def _show_next_question(self):
pass
def on_callback_query(self, msg):
pass
def on__idle(self, event):
pass
| 5 | 0 | 10 | 1 | 9 | 0 | 1 | 0 | 1 | 5 | 0 | 0 | 4 | 2 | 4 | 20 | 42 | 7 | 35 | 15 | 30 | 0 | 25 | 15 | 20 | 2 | 3 | 1 | 5 |
4,404 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/quiz.py
|
quiz.QuizStarter
|
class QuizStarter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(QuizStarter, self).__init__(*args, **kwargs)
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
self.sender.sendMessage(
'Press START to do some math ...',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[
InlineKeyboardButton(text='START', callback_data='start'),
]]
)
)
self.close()
|
class QuizStarter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
def on_chat_message(self, msg):
pass
| 3 | 0 | 7 | 0 | 7 | 1 | 1 | 0.07 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 19 | 15 | 1 | 14 | 4 | 11 | 1 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
4,405 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/payment/paymenta.py
|
paymenta.OrderProcessor
|
class OrderProcessor(amanobot.aio.helper.InvoiceHandler):
async def on_shipping_query(self, msg):
query_id, from_id, invoice_payload = amanobot.glance(msg, flavor='shipping_query')
print('Shipping query:')
pprint(msg)
await bot.answerShippingQuery(
query_id, True,
shipping_options=[
ShippingOption(id='fedex', title='FedEx', prices=[
LabeledPrice(label='Local', amount=345),
LabeledPrice(label='International', amount=2345)]),
ShippingOption(id='dhl', title='DHL', prices=[
LabeledPrice(label='Local', amount=342),
LabeledPrice(label='International', amount=1234)])])
async def on_pre_checkout_query(self, msg):
query_id, from_id, invoice_payload = amanobot.glance(msg, flavor='pre_checkout_query')
print('Pre-Checkout query:')
pprint(msg)
await bot.answerPreCheckoutQuery(query_id, True)
@staticmethod
def on_chat_message(msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type == 'successful_payment':
print('Successful payment RECEIVED!!!')
pprint(msg)
else:
print('Chat message:')
pprint(msg)
|
class OrderProcessor(amanobot.aio.helper.InvoiceHandler):
async def on_shipping_query(self, msg):
pass
async def on_pre_checkout_query(self, msg):
pass
@staticmethod
def on_chat_message(msg):
pass
| 5 | 0 | 10 | 2 | 9 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 3 | 18 | 36 | 8 | 28 | 8 | 23 | 0 | 18 | 7 | 14 | 2 | 3 | 1 | 4 |
4,406 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.BadHTTPResponse
|
class BadHTTPResponse(AmanobotException):
"""
All requests to Bot API should result in a JSON response. If non-JSON, this
exception is raised. While it is hard to pinpoint exactly when this might happen,
the following situations have been observed to give rise to it:
- an unreasonable token, e.g. ``abc``, ``123``, anything that does not even
remotely resemble a correct token.
- a bad gateway, e.g. when Telegram servers are down.
"""
@property
def status(self):
return self.args[0]
@property
def text(self):
return self.args[1]
@property
def response(self):
return self.args[2]
|
class BadHTTPResponse(AmanobotException):
'''
All requests to Bot API should result in a JSON response. If non-JSON, this
exception is raised. While it is hard to pinpoint exactly when this might happen,
the following situations have been observed to give rise to it:
- an unreasonable token, e.g. ``abc``, ``123``, anything that does not even
remotely resemble a correct token.
- a bad gateway, e.g. when Telegram servers are down.
'''
@property
def status(self):
pass
@property
def text(self):
pass
@property
def response(self):
pass
| 7 | 1 | 2 | 0 | 2 | 0 | 1 | 0.8 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 13 | 22 | 4 | 10 | 7 | 3 | 8 | 7 | 4 | 3 | 1 | 4 | 0 | 3 |
4,407 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/namedtuple.py
|
amanobot.namedtuple._Field
|
class _Field():
def __init__(self, name, constructor=None, default=None):
self.name = name
self.constructor = constructor
self.default = default
|
class _Field():
def __init__(self, name, constructor=None, default=None):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 3 | 1 | 1 | 5 | 0 | 5 | 5 | 3 | 0 | 5 | 5 | 3 | 1 | 0 | 0 | 1 |
4,408 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatbox_nodb.py
|
chatbox_nodb.ChatBox
|
class ChatBox(amanobot.DelegatorBot):
def __init__(self, token, owner_id):
self._owner_id = owner_id
self._seen = set()
self._store = UnreadStore()
super(ChatBox, self).__init__(token, [
# Here is a delegate to specially handle owner commands.
pave_event_space()(
per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20),
# Only one MessageSaver is ever spawned for entire application.
(per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])),
# For senders never seen before, send him a welcome message.
(self._is_newcomer, custom_thread(call(self._send_welcome))),
])
# seed-calculating function: use returned value to indicate whether to spawn a delegate
def _is_newcomer(self, msg):
if amanobot.is_event(msg):
return None
chat_id = msg['chat']['id']
if chat_id == self._owner_id: # Sender is owner
return None # No delegate spawned
if chat_id in self._seen: # Sender has been seen before
return None # No delegate spawned
self._seen.add(chat_id)
return [] # non-hashable ==> delegates are independent, no seed association is made.
def _send_welcome(self, seed_tuple):
chat_id = seed_tuple[1]['chat']['id']
print('Sending welcome ...')
self.sendMessage(chat_id, 'Hello!')
|
class ChatBox(amanobot.DelegatorBot):
def __init__(self, token, owner_id):
pass
def _is_newcomer(self, msg):
pass
def _send_welcome(self, seed_tuple):
pass
| 4 | 0 | 11 | 2 | 8 | 3 | 2 | 0.36 | 1 | 5 | 3 | 0 | 3 | 3 | 3 | 97 | 38 | 9 | 25 | 9 | 21 | 9 | 20 | 9 | 16 | 4 | 4 | 1 | 6 |
4,409 |
AmanoTeam/amanobot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmanoTeam_amanobot/amanobot/__init__.py
|
amanobot.Bot.Scheduler
|
class Scheduler(threading.Thread):
# A class that is sorted by timestamp. Use `bisect` module to ensure order in event queue.
Event = collections.namedtuple('Event', ['timestamp', 'data'])
Event.__eq__ = lambda self, other: self.timestamp == other.timestamp
Event.__ne__ = lambda self, other: self.timestamp != other.timestamp
Event.__gt__ = lambda self, other: self.timestamp > other.timestamp
Event.__ge__ = lambda self, other: self.timestamp >= other.timestamp
Event.__lt__ = lambda self, other: self.timestamp < other.timestamp
Event.__le__ = lambda self, other: self.timestamp <= other.timestamp
def __init__(self):
super(Bot.Scheduler, self).__init__()
self._eventq = []
# reentrant lock to allow locked method calling locked method
self._lock = threading.RLock()
self._event_handler = None
def _locked(fn):
def k(self, *args, **kwargs):
with self._lock:
return fn(self, *args, **kwargs)
return k
@_locked
def _insert_event(self, data, when):
ev = self.Event(when, data)
bisect.insort(self._eventq, ev)
return ev
@_locked
def _remove_event(self, event):
# Find event according to its timestamp.
# Index returned should be one behind.
i = bisect.bisect(self._eventq, event)
# Having two events with identical timestamp is unlikely but possible.
# I am going to move forward and compare timestamp AND object address
# to make sure the correct object is found.
while i > 0:
i -= 1
e = self._eventq[i]
if e.timestamp != event.timestamp:
raise exception.EventNotFound(event)
if id(e) == id(event):
self._eventq.pop(i)
return
raise exception.EventNotFound(event)
@_locked
def _pop_expired_event(self):
if not self._eventq:
return None
if self._eventq[0].timestamp <= time.time():
return self._eventq.pop(0)
return None
def event_at(self, when, data):
"""
Schedule some data to emit at an absolute timestamp.
:type when: int or float
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, when)
def event_later(self, delay, data):
"""
Schedule some data to emit after a number of seconds.
:type delay: int or float
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, time.time() + delay)
def event_now(self, data):
"""
Emit some data as soon as possible.
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, time.time())
def cancel(self, event):
"""
Cancel an event.
:type event: an internal Event object
"""
self._remove_event(event)
def run(self):
while 1:
e = self._pop_expired_event()
while e:
if callable(e.data):
d = e.data() # call the data-producing function
if d is not None:
self._event_handler(d)
else:
self._event_handler(e.data)
e = self._pop_expired_event()
time.sleep(0.1)
def run_as_thread(self):
self.daemon = True
self.start()
def on_event(self, fn):
self._event_handler = fn
|
class Scheduler(threading.Thread):
def __init__(self):
pass
def _locked(fn):
pass
def k(self, *args, **kwargs):
pass
@_locked
def _insert_event(self, data, when):
pass
@_locked
def _remove_event(self, event):
pass
@_locked
def _pop_expired_event(self):
pass
def event_at(self, when, data):
'''
Schedule some data to emit at an absolute timestamp.
:type when: int or float
:type data: dictionary
:return: an internal Event object
'''
pass
def event_later(self, delay, data):
'''
Schedule some data to emit after a number of seconds.
:type delay: int or float
:type data: dictionary
:return: an internal Event object
'''
pass
def event_now(self, data):
'''
Emit some data as soon as possible.
:type data: dictionary
:return: an internal Event object
'''
pass
def cancel(self, event):
'''
Cancel an event.
:type event: an internal Event object
'''
pass
def run(self):
pass
def run_as_thread(self):
pass
def on_event(self, fn):
pass
| 17 | 4 | 7 | 1 | 5 | 2 | 2 | 0.43 | 1 | 3 | 2 | 0 | 12 | 4 | 12 | 37 | 117 | 23 | 67 | 27 | 50 | 29 | 63 | 24 | 49 | 5 | 1 | 4 | 22 |
4,410 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/test/test3a_routing.py
|
test3a_routing.CommandHandler
|
class CommandHandler():
@staticmethod
def on_start(msg):
print('Command: start', msg)
@staticmethod
def on_settings(msg):
print('Command: settings', msg)
@staticmethod
def on_invalid_text(msg):
print('Invalid text', msg)
@staticmethod
def on_invalid_command(msg):
print('Invalid command', msg)
|
class CommandHandler():
@staticmethod
def on_start(msg):
pass
@staticmethod
def on_settings(msg):
pass
@staticmethod
def on_invalid_text(msg):
pass
@staticmethod
def on_invalid_command(msg):
pass
| 9 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 | 16 | 3 | 13 | 9 | 4 | 0 | 9 | 5 | 4 | 1 | 0 | 0 | 4 |
4,411 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/test/test3a_routing.py
|
test3a_routing.ContentTypeHandler
|
class ContentTypeHandler():
@staticmethod
def on_text(msg, text):
print('Text', msg, text)
@staticmethod
def on_photo(msg, photo):
print('Photo', msg, photo)
|
class ContentTypeHandler():
@staticmethod
def on_text(msg, text):
pass
@staticmethod
def on_photo(msg, photo):
pass
| 5 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 8 | 1 | 7 | 5 | 2 | 0 | 5 | 3 | 2 | 1 | 0 | 0 | 2 |
4,412 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/loop.py
|
amanobot.loop.CollectLoop
|
class CollectLoop(RunForeverAsThread):
def __init__(self, handle):
self._handle = handle
self._inqueue = queue.Queue()
@property
def input_queue(self):
return self._inqueue
def run_forever(self):
while 1:
try:
msg = self._inqueue.get(block=True)
self._handle(msg)
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
|
class CollectLoop(RunForeverAsThread):
def __init__(self, handle):
pass
@property
def input_queue(self):
pass
def run_forever(self):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 3 | 2 | 3 | 4 | 18 | 2 | 16 | 8 | 11 | 0 | 15 | 7 | 11 | 4 | 1 | 2 | 6 |
4,413 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatboxa_nodb.py
|
chatboxa_nodb.MessageSaver
|
class MessageSaver(amanobot.aio.helper.Monitor):
def __init__(self, seed_tuple, store, exclude):
# The `capture` criteria means to capture all messages.
super(MessageSaver, self).__init__(seed_tuple, capture=[[lambda msg: not amanobot.is_event(msg)]])
self._store = store
self._exclude = exclude
# Store every message, except those whose sender is in the exclude list, or non-text messages.
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if chat_id in self._exclude:
print('Chat id %d is excluded.' % chat_id)
return
if content_type != 'text':
print('Content type %s is ignored.' % content_type)
return
print('Storing message: %s' % msg)
self._store.put(msg)
|
class MessageSaver(amanobot.aio.helper.Monitor):
def __init__(self, seed_tuple, store, exclude):
pass
def on_chat_message(self, msg):
pass
| 3 | 0 | 9 | 2 | 7 | 1 | 2 | 0.13 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 10 | 21 | 4 | 15 | 6 | 12 | 2 | 15 | 6 | 12 | 3 | 2 | 1 | 4 |
4,414 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.StandardEventScheduler
|
class StandardEventScheduler():
"""
A proxy to the underlying :class:`.Bot`\'s scheduler, this object implements
the *standard event format*. A standard event looks like this::
{'_flavor': {
'source': {
'space': event_space, 'id': source_id}
'custom_key1': custom_value1,
'custom_key2': custom_value2,
... }}
- There is a single top-level key indicating the flavor, starting with an _underscore.
- On the second level, there is a ``source`` key indicating the event source.
- An event source consists of an *event space* and a *source id*.
- An event space is shared by all delegates in a group. Source id simply refers
to a delegate's id. They combine to ensure a delegate is always able to capture
its own events, while its own events would not be mistakenly captured by others.
Events scheduled through this object always have the second-level ``source`` key fixed,
while the flavor and other data may be customized.
"""
def __init__(self, scheduler, event_space, source_id):
self._base = scheduler
self._event_space = event_space
self._source_id = source_id
@property
def event_space(self):
return self._event_space
def configure(self, listener):
"""
Configure a :class:`.Listener` to capture events with this object's
event space and source id.
"""
listener.capture([{re.compile('^_.+'): {'source': {'space': self._event_space, 'id': self._source_id}}}])
def make_event_data(self, flavor, data):
"""
Marshall ``flavor`` and ``data`` into a standard event.
"""
if not flavor.startswith('_'):
raise ValueError('Event flavor must start with _underscore')
d = {'source': {'space': self._event_space, 'id': self._source_id}}
d.update(data)
return {flavor: d}
def event_at(self, when, data_tuple):
"""
Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_at(when, self.make_event_data(*data_tuple))
def event_later(self, delay, data_tuple):
"""
Schedule an event to be emitted after a delay.
:param delay: number of seconds
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_later(delay, self.make_event_data(*data_tuple))
def event_now(self, data_tuple):
"""
Schedule an event to be emitted now.
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
"""
return self._base.event_now(self.make_event_data(*data_tuple))
def cancel(self, event):
""" Cancel an event. """
return self._base.cancel(event)
|
class StandardEventScheduler():
'''
A proxy to the underlying :class:`.Bot`'s scheduler, this object implements
the *standard event format*. A standard event looks like this::
{'_flavor': {
'source': {
'space': event_space, 'id': source_id}
'custom_key1': custom_value1,
'custom_key2': custom_value2,
... }}
- There is a single top-level key indicating the flavor, starting with an _underscore.
- On the second level, there is a ``source`` key indicating the event source.
- An event source consists of an *event space* and a *source id*.
- An event space is shared by all delegates in a group. Source id simply refers
to a delegate's id. They combine to ensure a delegate is always able to capture
its own events, while its own events would not be mistakenly captured by others.
Events scheduled through this object always have the second-level ``source`` key fixed,
while the flavor and other data may be customized.
'''
def __init__(self, scheduler, event_space, source_id):
pass
@property
def event_space(self):
pass
def configure(self, listener):
'''
Configure a :class:`.Listener` to capture events with this object's
event space and source id.
'''
pass
def make_event_data(self, flavor, data):
'''
Marshall ``flavor`` and ``data`` into a standard event.
'''
pass
def event_at(self, when, data_tuple):
'''
Schedule an event to be emitted at a certain time.
:param when: an absolute timestamp
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
'''
pass
def event_later(self, delay, data_tuple):
'''
Schedule an event to be emitted after a delay.
:param delay: number of seconds
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
'''
pass
def event_now(self, data_tuple):
'''
Schedule an event to be emitted now.
:param data_tuple: a 2-tuple (flavor, data)
:return: an event object, useful for cancelling.
'''
pass
def cancel(self, event):
''' Cancel an event. '''
pass
| 10 | 7 | 6 | 1 | 3 | 3 | 1 | 1.79 | 0 | 1 | 0 | 0 | 8 | 3 | 8 | 8 | 81 | 14 | 24 | 14 | 14 | 43 | 23 | 13 | 14 | 2 | 0 | 1 | 9 |
4,415 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.StandardEventMixin
|
class StandardEventMixin():
"""
Install a :class:`.StandardEventScheduler`.
"""
StandardEventScheduler = StandardEventScheduler
def __init__(self, event_space, *args, **kwargs):
self._scheduler = self.StandardEventScheduler(self.bot.scheduler, event_space, self.id)
self._scheduler.configure(self.listener)
super(StandardEventMixin, self).__init__(*args, **kwargs)
@property
def scheduler(self):
return self._scheduler
|
class StandardEventMixin():
'''
Install a :class:`.StandardEventScheduler`.
'''
def __init__(self, event_space, *args, **kwargs):
pass
@property
def scheduler(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.33 | 0 | 1 | 0 | 8 | 2 | 1 | 2 | 2 | 14 | 2 | 9 | 6 | 5 | 3 | 8 | 5 | 5 | 1 | 0 | 0 | 2 |
4,416 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Sender
|
class Sender():
"""
When you are dealing with a particular chat, it is tedious to have to supply
the same ``chat_id`` every time to send a message, or to send anything.
This object is a proxy to a bot's ``send*`` and ``forwardMessage`` methods,
automatically fills in a fixed chat id for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``chat_id``:
- :meth:`.Bot.sendMessage`
- :meth:`.Bot.forwardMessage`
- :meth:`.Bot.sendPhoto`
- :meth:`.Bot.sendAudio`
- :meth:`.Bot.sendDocument`
- :meth:`.Bot.sendSticker`
- :meth:`.Bot.sendVideo`
- :meth:`.Bot.sendVoice`
- :meth:`.Bot.sendVideoNote`
- :meth:`.Bot.sendMediaGroup`
- :meth:`.Bot.sendLocation`
- :meth:`.Bot.sendVenue`
- :meth:`.Bot.sendContact`
- :meth:`.Bot.sendGame`
- :meth:`.Bot.sendChatAction`
"""
def __init__(self, bot, chat_id):
for method in ['sendMessage',
'forwardMessage',
'sendPhoto',
'sendAudio',
'sendDocument',
'sendSticker',
'sendVideo',
'sendVoice',
'sendVideoNote',
'sendMediaGroup',
'sendLocation',
'sendVenue',
'sendContact',
'sendGame',
'sendChatAction',]:
setattr(self, method, partial(getattr(bot, method), chat_id))
|
class Sender():
'''
When you are dealing with a particular chat, it is tedious to have to supply
the same ``chat_id`` every time to send a message, or to send anything.
This object is a proxy to a bot's ``send*`` and ``forwardMessage`` methods,
automatically fills in a fixed chat id for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``chat_id``:
- :meth:`.Bot.sendMessage`
- :meth:`.Bot.forwardMessage`
- :meth:`.Bot.sendPhoto`
- :meth:`.Bot.sendAudio`
- :meth:`.Bot.sendDocument`
- :meth:`.Bot.sendSticker`
- :meth:`.Bot.sendVideo`
- :meth:`.Bot.sendVoice`
- :meth:`.Bot.sendVideoNote`
- :meth:`.Bot.sendMediaGroup`
- :meth:`.Bot.sendLocation`
- :meth:`.Bot.sendVenue`
- :meth:`.Bot.sendContact`
- :meth:`.Bot.sendGame`
- :meth:`.Bot.sendChatAction`
'''
def __init__(self, bot, chat_id):
pass
| 2 | 1 | 17 | 0 | 17 | 0 | 2 | 1.28 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 44 | 3 | 18 | 3 | 16 | 23 | 4 | 3 | 2 | 2 | 0 | 1 | 2 |
4,417 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Router
|
class Router():
"""
Map a message to a handler function, using a **key function** and
a **routing table** (dictionary).
A *key function* digests a message down to a value. This value is treated
as a key to the *routing table* to look up a corresponding handler function.
"""
def __init__(self, key_function, routing_table):
"""
:param key_function:
A function that takes one argument (the message) and returns
one of the following:
- a key to the routing table
- a 1-tuple (key,)
- a 2-tuple (key, (positional, arguments, ...))
- a 3-tuple (key, (positional, arguments, ...), {keyword: arguments, ...})
Extra arguments, if returned, will be applied to the handler function
after using the key to look up the routing table.
:param routing_table:
A dictionary of ``{key: handler}``. A ``None`` key acts as a default
catch-all. If the key being looked up does not exist in the routing
table, the ``None`` key and its corresponding handler is used.
"""
super(Router, self).__init__()
self.key_function = key_function
self.routing_table = routing_table
def map(self, msg):
"""
Apply key function to ``msg`` to obtain a key. Return the routing table entry.
"""
k = self.key_function(msg)
key = k[0] if isinstance(k, (tuple, list)) else k
return self.routing_table[key]
def route(self, msg, *aa, **kw):
"""
Apply key function to ``msg`` to obtain a key, look up routing table
to obtain a handler function, then call the handler function with
positional and keyword arguments, if any is returned by the key function.
``*aa`` and ``**kw`` are dummy placeholders for easy chaining.
Regardless of any number of arguments returned by the key function,
multi-level routing may be achieved like this::
top_router.routing_table['key1'] = sub_router1.route
top_router.routing_table['key2'] = sub_router2.route
"""
k = self.key_function(msg)
if isinstance(k, (tuple, list)):
key, args, kwargs = {1: tuple(k) + ((),{}),
2: tuple(k) + ({},),
3: tuple(k),}[len(k)]
else:
key, args, kwargs = k, (), {}
try:
fn = self.routing_table[key]
except KeyError as e:
# Check for default handler, key=None
if None in self.routing_table:
fn = self.routing_table[None]
else:
raise RuntimeError('No handler for key: %s, and default handler not defined' % str(e.args))
return fn(msg, *args, **kwargs)
|
class Router():
'''
Map a message to a handler function, using a **key function** and
a **routing table** (dictionary).
A *key function* digests a message down to a value. This value is treated
as a key to the *routing table* to look up a corresponding handler function.
'''
def __init__(self, key_function, routing_table):
'''
:param key_function:
A function that takes one argument (the message) and returns
one of the following:
- a key to the routing table
- a 1-tuple (key,)
- a 2-tuple (key, (positional, arguments, ...))
- a 3-tuple (key, (positional, arguments, ...), {keyword: arguments, ...})
Extra arguments, if returned, will be applied to the handler function
after using the key to look up the routing table.
:param routing_table:
A dictionary of ``{key: handler}``. A ``None`` key acts as a default
catch-all. If the key being looked up does not exist in the routing
table, the ``None`` key and its corresponding handler is used.
'''
pass
def map(self, msg):
'''
Apply key function to ``msg`` to obtain a key. Return the routing table entry.
'''
pass
def route(self, msg, *aa, **kw):
'''
Apply key function to ``msg`` to obtain a key, look up routing table
to obtain a handler function, then call the handler function with
positional and keyword arguments, if any is returned by the key function.
``*aa`` and ``**kw`` are dummy placeholders for easy chaining.
Regardless of any number of arguments returned by the key function,
multi-level routing may be achieved like this::
top_router.routing_table['key1'] = sub_router1.route
top_router.routing_table['key2'] = sub_router2.route
'''
pass
| 4 | 4 | 20 | 3 | 8 | 10 | 2 | 1.4 | 0 | 6 | 0 | 1 | 3 | 2 | 3 | 3 | 72 | 12 | 25 | 12 | 21 | 35 | 21 | 11 | 17 | 4 | 0 | 2 | 7 |
4,418 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Microphone
|
class Microphone():
def __init__(self):
self._queues = set()
self._lock = threading.Lock()
def _locked(func):
def k(self, *args, **kwargs):
with self._lock:
return func(self, *args, **kwargs)
return k
@_locked
def add(self, q):
self._queues.add(q)
@_locked
def remove(self, q):
self._queues.remove(q)
@_locked
def send(self, msg):
for q in self._queues:
try:
q.put_nowait(msg)
except queue.Full:
traceback.print_exc()
|
class Microphone():
def __init__(self):
pass
def _locked(func):
pass
def k(self, *args, **kwargs):
pass
@_locked
def add(self, q):
pass
@_locked
def remove(self, q):
pass
@_locked
def send(self, msg):
pass
| 10 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | 5 | 2 | 5 | 5 | 26 | 4 | 22 | 13 | 12 | 0 | 19 | 10 | 12 | 3 | 0 | 2 | 8 |
4,419 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.ListenerContext
|
class ListenerContext():
def __init__(self, bot, context_id, *args, **kwargs):
# Initialize members before super() so mixin could use them.
self._bot = bot
self._id = context_id
self._listener = bot.create_listener()
super(ListenerContext, self).__init__(*args, **kwargs)
@property
def bot(self):
"""
The underlying :class:`.Bot` or an augmented version thereof
"""
return self._bot
@property
def id(self):
return self._id
@property
def listener(self):
""" See :class:`.Listener` """
return self._listener
|
class ListenerContext():
def __init__(self, bot, context_id, *args, **kwargs):
pass
@property
def bot(self):
'''
The underlying :class:`.Bot` or an augmented version thereof
'''
pass
@property
def id(self):
pass
@property
def listener(self):
''' See :class:`.Listener` '''
pass
| 8 | 2 | 4 | 0 | 3 | 1 | 1 | 0.33 | 0 | 1 | 0 | 6 | 4 | 3 | 4 | 4 | 23 | 3 | 15 | 11 | 7 | 5 | 12 | 8 | 7 | 1 | 0 | 0 | 4 |
4,420 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Listener
|
class Listener():
def __init__(self, mic, q):
self._mic = mic
self._queue = q
self._patterns = []
def __del__(self):
self._mic.remove(self._queue)
def capture(self, pattern):
"""
Add a pattern to capture.
:param pattern: a list of templates.
A template may be a function that:
- takes one argument - a message
- returns ``True`` to indicate a match
A template may also be a dictionary whose:
- **keys** are used to *select* parts of message. Can be strings or
regular expressions (as obtained by ``re.compile()``)
- **values** are used to match against the selected parts. Can be
typical data or a function.
All templates must produce a match for a message to be considered a match.
"""
self._patterns.append(pattern)
def wait(self):
"""
Block until a matched message appears.
"""
if not self._patterns:
raise RuntimeError('Listener has nothing to capture')
while 1:
msg = self._queue.get(block=True)
if any(map(lambda p: filtering.match_all(msg, p), self._patterns)):
return msg
|
class Listener():
def __init__(self, mic, q):
pass
def __del__(self):
pass
def capture(self, pattern):
'''
Add a pattern to capture.
:param pattern: a list of templates.
A template may be a function that:
- takes one argument - a message
- returns ``True`` to indicate a match
A template may also be a dictionary whose:
- **keys** are used to *select* parts of message. Can be strings or
regular expressions (as obtained by ``re.compile()``)
- **values** are used to match against the selected parts. Can be
typical data or a function.
All templates must produce a match for a message to be considered a match.
'''
pass
def wait(self):
'''
Block until a matched message appears.
'''
pass
| 5 | 2 | 9 | 2 | 4 | 4 | 2 | 1 | 0 | 2 | 0 | 1 | 4 | 3 | 4 | 4 | 41 | 9 | 16 | 9 | 11 | 16 | 16 | 9 | 11 | 4 | 0 | 2 | 7 |
4,421 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/loop.py
|
amanobot.loop.OrderedWebhook
|
class OrderedWebhook(RunForeverAsThread):
def __init__(self, bot, handle=None):
self._bot = bot
self._collectloop = CollectLoop(_infer_handler_function(bot, handle))
self._orderer = Orderer(lambda update:
self._collectloop.input_queue.put(_extract_message(update)[1]))
# feed messages to collect loop
def run_forever(self, *args, **kwargs):
"""
:type maxhold: float
:param maxhold:
The maximum number of seconds an update is held waiting for a
not-yet-arrived smaller ``update_id``. When this number of seconds
is up, the update is delivered to the message-handling function
even if some smaller ``update_id``\s have not yet arrived. If those
smaller ``update_id``\s arrive at some later time, they are discarded.
Calling this method will block forever. Use :meth:`.run_as_thread` to
run it non-blockingly.
"""
# feed events to collect loop
self._bot.scheduler.on_event(self._collectloop.input_queue.put)
self._bot.scheduler.run_as_thread()
self._orderer.run_as_thread(*args, **kwargs)
self._collectloop.run_forever()
def feed(self, data):
"""
:param data:
One of these:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
"""
update = _dictify(data)
self._orderer.input_queue.put(update)
|
class OrderedWebhook(RunForeverAsThread):
def __init__(self, bot, handle=None):
pass
def run_forever(self, *args, **kwargs):
'''
:type maxhold: float
:param maxhold:
The maximum number of seconds an update is held waiting for a
not-yet-arrived smaller ``update_id``. When this number of seconds
is up, the update is delivered to the message-handling function
even if some smaller ``update_id``\s have not yet arrived. If those
smaller ``update_id``\s arrive at some later time, they are discarded.
Calling this method will block forever. Use :meth:`.run_as_thread` to
run it non-blockingly.
'''
pass
def feed(self, data):
'''
:param data:
One of these:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
'''
pass
| 4 | 2 | 12 | 1 | 4 | 6 | 1 | 1.43 | 1 | 2 | 2 | 0 | 3 | 3 | 3 | 4 | 39 | 5 | 14 | 8 | 10 | 20 | 13 | 8 | 9 | 1 | 1 | 0 | 3 |
4,422 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/loop.py
|
amanobot.loop.Orderer
|
class Orderer(RunForeverAsThread):
def __init__(self, on_ordered_update):
self._on_ordered_update = on_ordered_update
self._inqueue = queue.Queue()
@property
def input_queue(self):
return self._inqueue
def run_forever(self, maxhold=3):
def handle(update):
self._on_ordered_update(update)
return update['update_id']
# Here is the re-ordering mechanism, ensuring in-order delivery of updates.
max_id = None # max update_id passed to callback
buffer = collections.deque() # keep those updates which skip some update_id
qwait = None # how long to wait for updates,
# because buffer's content has to be returned in time.
while 1:
try:
update = self._inqueue.get(block=True, timeout=qwait)
if max_id is None:
# First message received, handle regardless.
max_id = handle(update)
elif update['update_id'] == max_id + 1:
# No update_id skipped, handle naturally.
max_id = handle(update)
# clear contagious updates in buffer
if len(buffer) > 0:
buffer.popleft() # first element belongs to update just received, useless now.
while 1:
try:
if type(buffer[0]) is dict:
max_id = handle(buffer.popleft()) # updates that arrived earlier, handle them.
else:
break # gap, no more contagious updates
except IndexError:
break # buffer empty
elif update['update_id'] > max_id + 1:
# Update arrives pre-maturely, insert to buffer.
nbuf = len(buffer)
if update['update_id'] <= max_id + nbuf:
# buffer long enough, put update at position
buffer[update['update_id'] - max_id - 1] = update
else:
# buffer too short, lengthen it
expire = time.time() + maxhold
for a in range(nbuf, update['update_id']-max_id-1):
buffer.append(expire) # put expiry time in gaps
buffer.append(update)
else:
pass # discard
except queue.Empty:
# debug message
# print('Timeout')
# some buffer contents have to be handled
# flush buffer until a non-expired time is encountered
while 1:
try:
if type(buffer[0]) is dict:
max_id = handle(buffer.popleft())
else:
expire = buffer[0]
if expire <= time.time():
max_id += 1
buffer.popleft()
else:
break # non-expired
except IndexError:
break # buffer empty
except:
traceback.print_exc()
finally:
try:
# don't wait longer than next expiry time
qwait = buffer[0] - time.time()
qwait = max(qwait, 0)
except IndexError:
# buffer empty, can wait forever
qwait = None
|
class Orderer(RunForeverAsThread):
def __init__(self, on_ordered_update):
pass
@property
def input_queue(self):
pass
def run_forever(self, maxhold=3):
pass
def handle(update):
pass
| 6 | 0 | 22 | 2 | 16 | 6 | 5 | 0.39 | 1 | 5 | 0 | 0 | 3 | 2 | 3 | 4 | 89 | 11 | 64 | 15 | 58 | 25 | 55 | 14 | 50 | 18 | 1 | 7 | 21 |
4,423 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/loop.py
|
amanobot.loop.RunForeverAsThread
|
class RunForeverAsThread():
def run_as_thread(self, *args, **kwargs):
t = threading.Thread(target=self.run_forever, args=args, kwargs=kwargs)
t.daemon = True
t.start()
|
class RunForeverAsThread():
def run_as_thread(self, *args, **kwargs):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 6 | 1 | 1 | 1 | 1 | 5 | 0 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 0 | 0 | 1 |
4,424 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/__init__.py
|
amanobot._BotBase
|
class _BotBase:
def __init__(self, token: str, raise_errors: bool, api_endpoint: str):
self._token = token
self._raise_errors = raise_errors
self._base_url = api_endpoint
self._file_chunk_size = 65536
|
class _BotBase:
def __init__(self, token: str, raise_errors: bool, api_endpoint: str):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 2 | 0 | 2 | 1 | 4 | 1 | 1 | 6 | 0 | 6 | 6 | 4 | 0 | 6 | 6 | 4 | 1 | 0 | 0 | 1 |
4,425 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/loop.py
|
amanobot.loop.GetUpdatesLoop
|
class GetUpdatesLoop(RunForeverAsThread):
def __init__(self, bot, on_update):
self._bot = bot
self._update_handler = on_update
def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None):
"""
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool
"""
while 1:
try:
result = self._bot.getUpdates(offset=offset,
timeout=timeout,
allowed_updates=allowed_updates,
_raise_errors=True)
# Once passed, this parameter is no longer needed.
allowed_updates = None
# No sort. Trust server to give messages in correct order.
for update in result:
self._update_handler(update)
offset = update['update_id'] + 1
except exception.BadHTTPResponse as e:
traceback.print_exc()
# Servers probably down. Wait longer.
if e.status == 502:
time.sleep(30)
except:
traceback.print_exc()
finally:
time.sleep(relax)
|
class GetUpdatesLoop(RunForeverAsThread):
def __init__(self, bot, on_update):
pass
def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None):
'''
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool
'''
pass
| 3 | 1 | 19 | 3 | 11 | 5 | 4 | 0.43 | 1 | 1 | 1 | 0 | 2 | 2 | 2 | 3 | 39 | 6 | 23 | 8 | 20 | 10 | 19 | 7 | 16 | 6 | 1 | 3 | 7 |
4,426 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/__init__.py
|
amanobot.Bot
|
class Bot(_BotBase):
class Scheduler(threading.Thread):
# A class that is sorted by timestamp. Use `bisect` module to ensure order in event queue.
Event = collections.namedtuple('Event', ['timestamp', 'data'])
Event.__eq__ = lambda self, other: self.timestamp == other.timestamp
Event.__ne__ = lambda self, other: self.timestamp != other.timestamp
Event.__gt__ = lambda self, other: self.timestamp > other.timestamp
Event.__ge__ = lambda self, other: self.timestamp >= other.timestamp
Event.__lt__ = lambda self, other: self.timestamp < other.timestamp
Event.__le__ = lambda self, other: self.timestamp <= other.timestamp
def __init__(self):
super(Bot.Scheduler, self).__init__()
self._eventq = []
self._lock = threading.RLock() # reentrant lock to allow locked method calling locked method
self._event_handler = None
def _locked(fn):
def k(self, *args, **kwargs):
with self._lock:
return fn(self, *args, **kwargs)
return k
@_locked
def _insert_event(self, data, when):
ev = self.Event(when, data)
bisect.insort(self._eventq, ev)
return ev
@_locked
def _remove_event(self, event):
# Find event according to its timestamp.
# Index returned should be one behind.
i = bisect.bisect(self._eventq, event)
# Having two events with identical timestamp is unlikely but possible.
# I am going to move forward and compare timestamp AND object address
# to make sure the correct object is found.
while i > 0:
i -= 1
e = self._eventq[i]
if e.timestamp != event.timestamp:
raise exception.EventNotFound(event)
if id(e) == id(event):
self._eventq.pop(i)
return
raise exception.EventNotFound(event)
@_locked
def _pop_expired_event(self):
if not self._eventq:
return None
if self._eventq[0].timestamp <= time.time():
return self._eventq.pop(0)
return None
def event_at(self, when, data):
"""
Schedule some data to emit at an absolute timestamp.
:type when: int or float
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, when)
def event_later(self, delay, data):
"""
Schedule some data to emit after a number of seconds.
:type delay: int or float
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, time.time() + delay)
def event_now(self, data):
"""
Emit some data as soon as possible.
:type data: dictionary
:return: an internal Event object
"""
return self._insert_event(data, time.time())
def cancel(self, event):
"""
Cancel an event.
:type event: an internal Event object
"""
self._remove_event(event)
def run(self):
while 1:
e = self._pop_expired_event()
while e:
if callable(e.data):
d = e.data() # call the data-producing function
if d is not None:
self._event_handler(d)
else:
self._event_handler(e.data)
e = self._pop_expired_event()
time.sleep(0.1)
def run_as_thread(self):
self.daemon = True
self.start()
def on_event(self, fn):
self._event_handler = fn
def __init__(self, token: str, raise_errors: bool = True, api_endpoint: str = "https://api.telegram.org"):
super(Bot, self).__init__(token, raise_errors, api_endpoint)
self._scheduler = self.Scheduler()
self._router = helper.Router(flavor, {'chat': lambda msg: self.on_chat_message(msg),
'callback_query': lambda msg: self.on_callback_query(msg),
'inline_query': lambda msg: self.on_inline_query(msg),
'chosen_inline_result': lambda msg: self.on_chosen_inline_result(msg)})
# use lambda to delay evaluation of self.on_ZZZ to runtime because
# I don't want to require defining all methods right here.
@property
def scheduler(self):
return self._scheduler
@property
def router(self):
return self._router
def handle(self, msg):
self._router.route(msg)
def _api_request(self, method, params=None, files=None, raise_errors=None, **kwargs):
return api.request((self._base_url, self._token, method, params, files),
raise_errors=raise_errors if raise_errors is not None else self._raise_errors, **kwargs)
def _api_request_with_file(self, method, params, files, **kwargs):
params.update({
k: v for k, v in files.items() if _isstring(v)})
files = {
k: v for k, v in files.items() if v is not None and not _isstring(v)}
return self._api_request(method, _rectify(params), files, **kwargs)
def getMe(self):
""" See: https://core.telegram.org/bots/api#getme """
return self._api_request('getMe')
def logOut(self):
""" See: https://core.telegram.org/bots/api#logout """
return self._api_request('logOut')
def close(self):
""" See: https://core.telegram.org/bots/api#close """
return self._api_request('close')
def sendMessage(self, chat_id: Union[int, str], text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendmessage """
p = _strip(locals())
return self._api_request('sendMessage', _rectify(p))
def forwardMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
""" See: https://core.telegram.org/bots/api#forwardmessage """
p = _strip(locals())
return self._api_request('forwardMessage', _rectify(p))
def copyMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#copymessage """
p = _strip(locals())
return self._api_request('copyMessage', _rectify(p))
def sendPhoto(self, chat_id: Union[int, str], photo,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendphoto
:param photo:
- string: ``file_id`` for a photo existing on Telegram servers
- string: HTTP URL of a photo from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (filename, file-like object).
"""
p = _strip(locals(), more=['photo'])
return self._api_request_with_file('sendPhoto', _rectify(p), {'photo': photo})
def sendAudio(self, chat_id: Union[int, str], audio,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
performer=None,
title=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendaudio
:param audio: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['audio', 'thumb'])
return self._api_request_with_file('sendAudio', _rectify(p), {'audio': audio, 'thumb': thumb})
def sendDocument(self, chat_id: Union[int, str], document,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_content_type_detection=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#senddocument
:param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['document', 'thumb'])
return self._api_request_with_file('sendDocument', _rectify(p), {'document': document, 'thumb': thumb})
def sendVideo(self, chat_id: Union[int, str], video,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
supports_streaming=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvideo
:param video: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['video', 'thumb'])
return self._api_request_with_file('sendVideo', _rectify(p), {'video': video, 'thumb': thumb})
def sendAnimation(self, chat_id: Union[int, str], animation,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendanimation
:param animation: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['animation', 'thumb'])
return self._api_request_with_file('sendAnimation', _rectify(p), {'animation': animation, 'thumb': thumb})
def sendVoice(self, chat_id: Union[int, str], voice,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvoice
:param voice: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['voice'])
return self._api_request_with_file('sendVoice', _rectify(p), {'voice': voice})
def sendVideoNote(self, chat_id: Union[int, str], video_note,
duration=None,
length=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvideonote
:param video_note: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
:param length:
Although marked as optional, this method does not seem to work without
it being specified. Supply any integer you want. It seems to have no effect
on the video note's display size.
"""
p = _strip(locals(), more=['video_note', 'thumb'])
return self._api_request_with_file('sendVideoNote', _rectify(p), {'video_note': video_note, 'thumb': thumb})
def sendMediaGroup(self, chat_id: Union[int, str], media,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None):
"""
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
:param media:
To indicate media locations, each InputMedia object's ``media`` field
should be one of these:
- string: ``file_id`` for a file existing on Telegram servers
- string: HTTP URL of a file from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (form-data name, file-like object)
- tuple: (form-data name, (filename, file-like object))
In case of uploading, you may supply customized multipart/form-data
names for each uploaded file (as in last 2 options above). Otherwise,
amanobot assigns unique names to each uploaded file. Names assigned by
amanobot will not collide with user-supplied names, if any.
"""
p = _strip(locals(), more=['media'])
legal_media, files_to_attach = _split_input_media_array(media)
p['media'] = legal_media
return self._api_request('sendMediaGroup', _rectify(p), files_to_attach)
def sendLocation(self, chat_id: Union[int, str], latitude, longitude,
horizontal_accuracy=None,
live_period=None,
heading=None,
proximity_alert_radius=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendlocation """
p = _strip(locals())
return self._api_request('sendLocation', _rectify(p))
def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
horizontal_accuracy=None,
heading=None,
proximity_alert_radius=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('editMessageLiveLocation', _rectify(p))
def stopMessageLiveLocation(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stopmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('stopMessageLiveLocation', _rectify(p))
def sendVenue(self, chat_id: Union[int, str], latitude, longitude, title, address,
foursquare_id=None,
foursquare_type=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendvenue """
p = _strip(locals())
return self._api_request('sendVenue', _rectify(p))
def sendContact(self, chat_id: Union[int, str], phone_number, first_name,
last_name=None,
vcard=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendcontact """
p = _strip(locals())
return self._api_request('sendContact', _rectify(p))
def sendPoll(self, chat_id: Union[int, str], question, options,
is_anonymous=None,
type=None,
allows_multiple_answers=None,
correct_option_id=None,
explanation=None,
explanation_parse_mode: str = None,
open_period=None,
is_closed=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendpoll """
p = _strip(locals())
return self._api_request('sendPoll', _rectify(p))
def sendDice(self, chat_id: Union[int, str],
emoji=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#senddice """
p = _strip(locals())
return self._api_request('sendDice', _rectify(p))
def sendGame(self, chat_id: Union[int, str], game_short_name,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendgame """
p = _strip(locals())
return self._api_request('sendGame', _rectify(p))
def sendInvoice(self, chat_id: Union[int, str], title, description, payload,
provider_token, start_parameter, currency, prices,
provider_data=None,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,
need_name=None,
need_phone_number=None,
need_email=None,
need_shipping_address=None,
is_flexible=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendinvoice """
p = _strip(locals())
return self._api_request('sendInvoice', _rectify(p))
def sendChatAction(self, chat_id: Union[int, str], action):
""" See: https://core.telegram.org/bots/api#sendchataction """
p = _strip(locals())
return self._api_request('sendChatAction', _rectify(p))
def getUserProfilePhotos(self, user_id,
offset=None,
limit=None):
""" See: https://core.telegram.org/bots/api#getuserprofilephotos """
p = _strip(locals())
return self._api_request('getUserProfilePhotos', _rectify(p))
def getFile(self, file_id):
""" See: https://core.telegram.org/bots/api#getfile """
p = _strip(locals())
return self._api_request('getFile', _rectify(p))
def kickChatMember(self, chat_id: Union[int, str], user_id,
until_date: int = None,
revoke_messages: bool = None):
""" See: https://core.telegram.org/bots/api#kickchatmember """
p = _strip(locals())
return self._api_request('kickChatMember', _rectify(p))
def unbanChatMember(self, chat_id: Union[int, str], user_id,
only_if_banned=None):
""" See: https://core.telegram.org/bots/api#unbanchatmember """
p = _strip(locals())
return self._api_request('unbanChatMember', _rectify(p))
def restrictChatMember(self, chat_id: Union[int, str], user_id,
until_date=None,
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
""" See: https://core.telegram.org/bots/api#restrictchatmember """
if not isinstance(permissions, dict):
permissions = dict(can_send_messages=can_send_messages,
can_send_media_messages=can_send_media_messages,
can_send_polls=can_send_polls,
can_send_other_messages=can_send_other_messages,
can_add_web_page_previews=can_add_web_page_previews,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages)
p = _strip(locals())
return self._api_request('restrictChatMember', _rectify(p))
def promoteChatMember(self, chat_id: Union[int, str], user_id,
is_anonymous=None,
can_manage_chat=None,
can_post_messages=None,
can_edit_messages=None,
can_delete_messages=None,
can_manage_voice_chats=None,
can_restrict_members=None,
can_promote_members=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None):
""" See: https://core.telegram.org/bots/api#promotechatmember """
p = _strip(locals())
return self._api_request('promoteChatMember', _rectify(p))
def setChatAdministratorCustomTitle(self, chat_id: Union[int, str], user_id,
custom_title):
""" See: https://core.telegram.org/bots/api#setchatadministratorcustomtitle """
p = _strip(locals())
return self._api_request('setChatAdministratorCustomTitle', _rectify(p))
def setChatPermissions(self, chat_id: Union[int, str],
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
""" See: https://core.telegram.org/bots/api#setchatpermissions """
if not isinstance(permissions, dict):
permissions = dict(can_send_messages=can_send_messages,
can_send_media_messages=can_send_media_messages,
can_send_polls=can_send_polls,
can_send_other_messages=can_send_other_messages,
can_add_web_page_previews=can_add_web_page_previews,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages)
p = _strip(locals())
return self._api_request('setChatPermissions', _rectify(p))
def exportChatInviteLink(self, chat_id):
""" See: https://core.telegram.org/bots/api#exportchatinvitelink """
p = _strip(locals())
return self._api_request('exportChatInviteLink', _rectify(p))
def createChatInviteLink(self, chat_id,
expire_date: int = None,
member_limit: int = None):
""" See: https://core.telegram.org/bots/api#createchatinvitelink """
p = _strip(locals())
return self._api_request('createChatInviteLink', _rectify(p))
def editChatInviteLink(self, chat_id,
invite_link: str,
expire_date: int = None,
member_limit: int = None):
""" See: https://core.telegram.org/bots/api#editchatinvitelink """
p = _strip(locals())
return self._api_request('editChatInviteLink', _rectify(p))
def revokeChatInviteLink(self, chat_id, invite_link: str):
""" See: https://core.telegram.org/bots/api#revokechatinvitelink """
p = _strip(locals())
return self._api_request('revokeChatInviteLink', _rectify(p))
def setChatPhoto(self, chat_id: Union[int, str], photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return self._api_request_with_file('setChatPhoto', _rectify(p), {'photo': photo})
def deleteChatPhoto(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatphoto """
p = _strip(locals())
return self._api_request('deleteChatPhoto', _rectify(p))
def setChatTitle(self, chat_id: Union[int, str], title):
""" See: https://core.telegram.org/bots/api#setchattitle """
p = _strip(locals())
return self._api_request('setChatTitle', _rectify(p))
def setChatDescription(self, chat_id: Union[int, str],
description=None):
""" See: https://core.telegram.org/bots/api#setchatdescription """
p = _strip(locals())
return self._api_request('setChatDescription', _rectify(p))
def pinChatMessage(self, chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
""" See: https://core.telegram.org/bots/api#pinchatmessage """
p = _strip(locals())
return self._api_request('pinChatMessage', _rectify(p))
def unpinChatMessage(self, chat_id: Union[int, str],
message_id=None):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return self._api_request('unpinChatMessage', _rectify(p))
def unpinAllChatMessages(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinallchatmessages """
p = _strip(locals())
return self._api_request('unpinAllChatMessages', _rectify(p))
def leaveChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#leavechat """
p = _strip(locals())
return self._api_request('leaveChat', _rectify(p))
def getChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchat """
p = _strip(locals())
return self._api_request('getChat', _rectify(p))
def getChatAdministrators(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatadministrators """
p = _strip(locals())
return self._api_request('getChatAdministrators', _rectify(p))
def getChatMembersCount(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatmemberscount """
p = _strip(locals())
return self._api_request('getChatMembersCount', _rectify(p))
def getChatMember(self, chat_id: Union[int, str], user_id):
""" See: https://core.telegram.org/bots/api#getchatmember """
p = _strip(locals())
return self._api_request('getChatMember', _rectify(p))
def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
""" See: https://core.telegram.org/bots/api#setchatstickerset """
p = _strip(locals())
return self._api_request('setChatStickerSet', _rectify(p))
def deleteChatStickerSet(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatstickerset """
p = _strip(locals())
return self._api_request('deleteChatStickerSet', _rectify(p))
def answerCallbackQuery(self, callback_query_id,
text=None,
show_alert=None,
url=None,
cache_time=None):
""" See: https://core.telegram.org/bots/api#answercallbackquery """
p = _strip(locals())
return self._api_request('answerCallbackQuery', _rectify(p))
def setMyCommands(self, commands=None):
""" See: https://core.telegram.org/bots/api#setmycommands """
if commands is None:
commands = []
p = _strip(locals())
return self._api_request('setMyCommands', _rectify(p))
def getMyCommands(self):
""" See: https://core.telegram.org/bots/api#getmycommands """
return self._api_request('getMyCommands')
def setPassportDataErrors(self, user_id, errors):
""" See: https://core.telegram.org/bots/api#setpassportdataerrors """
p = _strip(locals())
return self._api_request('setPassportDataErrors', _rectify(p))
def answerShippingQuery(self, shipping_query_id, ok,
shipping_options=None,
error_message=None):
""" See: https://core.telegram.org/bots/api#answershippingquery """
p = _strip(locals())
return self._api_request('answerShippingQuery', _rectify(p))
def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
""" See: https://core.telegram.org/bots/api#answerprecheckoutquery """
p = _strip(locals())
return self._api_request('answerPreCheckoutQuery', _rectify(p))
def editMessageText(self, msg_identifier, text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`amanobot.message_identifier`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('editMessageText', _rectify(p))
def editMessageCaption(self, msg_identifier,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('editMessageCaption', _rectify(p))
def editMessageMedia(self, msg_identifier, media,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier', 'media'])
p.update(_dismantle_message_identifier(msg_identifier))
legal_media, files_to_attach = _split_input_media_array([media])
p['media'] = legal_media[0]
return self._api_request('editMessageMedia', _rectify(p), files_to_attach)
def editMessageReplyMarkup(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagereplymarkup
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('editMessageReplyMarkup', _rectify(p))
def stopPoll(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``).
You may extract this value easily with :meth:`amanobot.message_identifier`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('stopPoll', _rectify(p))
def deleteMessage(self, msg_identifier):
"""
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`,
except this method does not work on inline messages.
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return self._api_request('deleteMessage', _rectify(p))
def sendSticker(self, chat_id: Union[int, str], sticker,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
"""
p = _strip(locals(), more=['sticker'])
return self._api_request_with_file('sendSticker', _rectify(p), {'sticker': sticker})
def getStickerSet(self, name):
"""
See: https://core.telegram.org/bots/api#getstickerset
"""
p = _strip(locals())
return self._api_request('getStickerSet', _rectify(p))
def uploadStickerFile(self, user_id, png_sticker):
"""
See: https://core.telegram.org/bots/api#uploadstickerfile
"""
p = _strip(locals(), more=['png_sticker'])
return self._api_request_with_file('uploadStickerFile', _rectify(p), {'png_sticker': png_sticker})
def createNewStickerSet(self, user_id, name, title, emojis,
png_sticker=None,
tgs_sticker=None,
contains_masks=None,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#createnewstickerset
"""
p = _strip(locals(), more=['png_sticker', 'tgs_sticker'])
return self._api_request_with_file('createNewStickerSet', _rectify(p),
{'png_sticker': png_sticker, 'tgs_sticker': tgs_sticker})
def addStickerToSet(self, user_id, name, emojis,
png_sticker=None,
tgs_sticker=None,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#addstickertoset
"""
p = _strip(locals(), more=['png_sticker', 'tgs_sticker'])
return self._api_request_with_file('addStickerToSet', _rectify(p),
{'png_sticker': png_sticker, 'tgs_sticker': tgs_sticker})
def setStickerPositionInSet(self, sticker, position):
"""
See: https://core.telegram.org/bots/api#setstickerpositioninset
"""
p = _strip(locals())
return self._api_request('setStickerPositionInSet', _rectify(p))
def deleteStickerFromSet(self, sticker):
"""
See: https://core.telegram.org/bots/api#deletestickerfromset
"""
p = _strip(locals())
return self._api_request('deleteStickerFromSet', _rectify(p))
def setStickerSetThumb(self, name, user_id,
thumb=None):
"""
See: https://core.telegram.org/bots/api#setstickersetthumb
"""
p = _strip(locals(), more=['thumb'])
return self._api_request_with_file('setStickerSetThumb', _rectify(p), {'thumb': thumb})
def answerInlineQuery(self, inline_query_id, results,
cache_time=None,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None):
""" See: https://core.telegram.org/bots/api#answerinlinequery """
p = _strip(locals())
return self._api_request('answerInlineQuery', _rectify(p))
def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None,
_raise_errors=None):
""" See: https://core.telegram.org/bots/api#getupdates """
if _raise_errors is None:
_raise_errors = self._raise_errors
p = _strip(locals())
return self._api_request('getUpdates', _rectify(p), raise_errors=_raise_errors)
def setWebhook(self,
url=None,
certificate=None,
ip_address=None,
max_connections=None,
allowed_updates=None,
drop_pending_updates=None):
""" See: https://core.telegram.org/bots/api#setwebhook """
p = _strip(locals(), more=['certificate'])
if certificate:
files = {'certificate': certificate}
return self._api_request('setWebhook', _rectify(p), files)
return self._api_request('setWebhook', _rectify(p))
def deleteWebhook(self,
drop_pending_updates=None):
p = _strip(locals())
""" See: https://core.telegram.org/bots/api#deletewebhook """
return self._api_request('deleteWebhook', _rectify(p))
def getWebhookInfo(self):
""" See: https://core.telegram.org/bots/api#getwebhookinfo """
return self._api_request('getWebhookInfo')
def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
"""
See: https://core.telegram.org/bots/api#setgamescore
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
"""
p = _strip(locals(), more=['game_message_identifier'])
p.update(_dismantle_message_identifier(game_message_identifier))
return self._api_request('setGameScore', _rectify(p))
def getGameHighScores(self, user_id, game_message_identifier):
"""
See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
"""
p = _strip(locals(), more=['game_message_identifier'])
p.update(_dismantle_message_identifier(game_message_identifier))
return self._api_request('getGameHighScores', _rectify(p))
def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = self.getFile(file_id)
try:
d = dest if _isfile(dest) else open(dest, 'wb')
r = api.download((self._base_url, self._token, f['file_path']), preload_content=False)
while 1:
data = r.read(self._file_chunk_size)
if not data:
break
d.write(data)
finally:
if not _isfile(dest) and 'd' in locals():
d.close()
if 'r' in locals():
r.release_conn()
def message_loop(self, callback=None, relax=0.1,
timeout=20, allowed_updates=None,
source=None, ordered=True, maxhold=3,
run_forever=False):
"""
:deprecated: will be removed in future. Use :class:`.MessageLoop` instead.
Spawn a thread to constantly ``getUpdates`` or pull updates from a queue.
Apply ``callback`` to every message received. Also starts the scheduler thread
for internal events.
:param callback:
a function that takes one argument (the message), or a routing table.
If ``None``, the bot's ``handle`` method is used.
A *routing table* is a dictionary of ``{flavor: function}``, mapping messages to appropriate
handler functions according to their flavors. It allows you to define functions specifically
to handle one flavor of messages. It usually looks like this: ``{'chat': fn1,
'callback_query': fn2, 'inline_query': fn3, ...}``. Each handler function should take
one argument (the message).
:param source:
Source of updates.
If ``None``, ``getUpdates`` is used to obtain new messages from Telegram servers.
If it is a synchronized queue, new messages are pulled from the queue.
A web application implementing a webhook can dump updates into the queue,
while the bot pulls from it. This is how amanobot can be integrated with webhooks.
Acceptable contents in queue:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
When ``source`` is ``None``, these parameters are meaningful:
:type relax: float
:param relax: seconds between each ``getUpdates``
:type timeout: int
:param timeout:
``timeout`` parameter supplied to :meth:`amanobot.Bot.getUpdates`,
controlling how long to poll.
:type allowed_updates: array of string
:param allowed_updates:
``allowed_updates`` parameter supplied to :meth:`amanobot.Bot.getUpdates`,
controlling which types of updates to receive.
When ``source`` is a queue, these parameters are meaningful:
:type ordered: bool
:param ordered:
If ``True``, ensure in-order delivery of messages to ``callback``
(i.e. updates with a smaller ``update_id`` always come before those with
a larger ``update_id``).
If ``False``, no re-ordering is done. ``callback`` is applied to messages
as soon as they are pulled from queue.
:type maxhold: float
:param maxhold:
Applied only when ``ordered`` is ``True``. The maximum number of seconds
an update is held waiting for a not-yet-arrived smaller ``update_id``.
When this number of seconds is up, the update is delivered to ``callback``
even if some smaller ``update_id``\s have not yet arrived. If those smaller
``update_id``\s arrive at some later time, they are discarded.
Finally, there is this parameter, meaningful always:
:type run_forever: bool or str
:param run_forever:
If ``True`` or any non-empty string, append an infinite loop at the end of
this method, so it never returns. Useful as the very last line in a program.
A non-empty string will also be printed, useful as an indication that the
program is listening.
"""
if callback is None:
callback = self.handle
elif isinstance(callback, dict):
callback = flavor_router(callback)
collect_queue = queue.Queue()
def collector():
while 1:
try:
item = collect_queue.get(block=True)
callback(item)
except:
# Localize error so thread can keep going.
traceback.print_exc()
def relay_to_collector(update):
key = _find_first_key(update, ['message',
'edited_message',
'channel_post',
'edited_channel_post',
'inline_query',
'chosen_inline_result',
'callback_query',
'shipping_query',
'pre_checkout_query',
'poll',
'poll_answer',
'my_chat_member',
'chat_member'])
collect_queue.put(update[key])
return update['update_id']
def get_from_telegram_server():
offset = None # running offset
allowed_upd = allowed_updates
while 1:
try:
result = self.getUpdates(offset=offset,
timeout=timeout,
allowed_updates=allowed_upd,
_raise_errors=True)
# Once passed, this parameter is no longer needed.
allowed_upd = None
if len(result) > 0:
# No sort. Trust server to give messages in correct order.
# Update offset to max(update_id) + 1
offset = max([relay_to_collector(update) for update in result]) + 1
except exception.BadHTTPResponse as e:
traceback.print_exc()
# Servers probably down. Wait longer.
if e.status == 502:
time.sleep(30)
except:
traceback.print_exc()
finally:
time.sleep(relax)
def dictify(data):
if type(data) is bytes:
return json.loads(data.decode('utf-8'))
if type(data) is str:
return json.loads(data)
if type(data) is dict:
return data
raise ValueError()
def get_from_queue_unordered(qu):
while 1:
try:
data = qu.get(block=True)
update = dictify(data)
relay_to_collector(update)
except:
traceback.print_exc()
def get_from_queue(qu):
# Here is the re-ordering mechanism, ensuring in-order delivery of updates.
max_id = None # max update_id passed to callback
buffer = collections.deque() # keep those updates which skip some update_id
qwait = None # how long to wait for updates,
# because buffer's content has to be returned in time.
while 1:
try:
data = qu.get(block=True, timeout=qwait)
update = dictify(data)
if max_id is None:
# First message received, handle regardless.
max_id = relay_to_collector(update)
elif update['update_id'] == max_id + 1:
# No update_id skipped, handle naturally.
max_id = relay_to_collector(update)
# clear contagious updates in buffer
if len(buffer) > 0:
buffer.popleft() # first element belongs to update just received, useless now.
while 1:
try:
if type(buffer[0]) is dict:
max_id = relay_to_collector(
buffer.popleft()) # updates that arrived earlier, handle them.
else:
break # gap, no more contagious updates
except IndexError:
break # buffer empty
elif update['update_id'] > max_id + 1:
# Update arrives pre-maturely, insert to buffer.
nbuf = len(buffer)
if update['update_id'] <= max_id + nbuf:
# buffer long enough, put update at position
buffer[update['update_id'] - max_id - 1] = update
else:
# buffer too short, lengthen it
expire = time.time() + maxhold
for a in range(nbuf, update['update_id'] - max_id - 1):
buffer.append(expire) # put expiry time in gaps
buffer.append(update)
else:
pass # discard
except queue.Empty:
# debug message
# print('Timeout')
# some buffer contents have to be handled
# flush buffer until a non-expired time is encountered
while 1:
try:
if type(buffer[0]) is dict:
max_id = relay_to_collector(buffer.popleft())
else:
expire = buffer[0]
if expire <= time.time():
max_id += 1
buffer.popleft()
else:
break # non-expired
except IndexError:
break # buffer empty
except:
traceback.print_exc()
finally:
try:
# don't wait longer than next expiry time
qwait = buffer[0] - time.time()
qwait = max(qwait, 0)
except IndexError:
# buffer empty, can wait forever
qwait = None
# debug message
# print ('Buffer:', str(buffer), ', To Wait:', qwait, ', Max ID:', max_id)
collector_thread = threading.Thread(target=collector)
collector_thread.daemon = True
collector_thread.start()
if source is None:
message_thread = threading.Thread(target=get_from_telegram_server)
elif isinstance(source, queue.Queue):
if ordered:
message_thread = threading.Thread(target=get_from_queue, args=(source,))
else:
message_thread = threading.Thread(target=get_from_queue_unordered, args=(source,))
else:
raise ValueError('Invalid source')
message_thread.daemon = True # need this for main thread to be killable by Ctrl-C
message_thread.start()
self._scheduler.on_event(collect_queue.put)
self._scheduler.run_as_thread()
if run_forever:
if _isstring(run_forever):
print(run_forever)
while 1:
time.sleep(10)
|
class Bot(_BotBase):
class Scheduler(threading.Thread):
def __init__(self):
pass
def _locked(fn):
pass
def k(self, *args, **kwargs):
pass
@_locked
def _insert_event(self, data, when):
pass
@_locked
def _remove_event(self, event):
pass
@_locked
def _pop_expired_event(self):
pass
def event_at(self, when, data):
'''
Schedule some data to emit at an absolute timestamp.
:type when: int or float
:type data: dictionary
:return: an internal Event object
'''
pass
def event_later(self, delay, data):
'''
Schedule some data to emit after a number of seconds.
:type delay: int or float
:type data: dictionary
:return: an internal Event object
'''
pass
def event_now(self, data):
'''
Emit some data as soon as possible.
:type data: dictionary
:return: an internal Event object
'''
pass
def cancel(self, event):
'''
Cancel an event.
:type event: an internal Event object
'''
pass
def run(self):
pass
def run_as_thread(self):
pass
def on_event(self, fn):
pass
def __init__(self):
pass
@property
def scheduler(self):
pass
@property
def router(self):
pass
def handle(self, msg):
pass
def _api_request(self, method, params=None, files=None, raise_errors=None, **kwargs):
pass
def _api_request_with_file(self, method, params, files, **kwargs):
pass
def getMe(self):
''' See: https://core.telegram.org/bots/api#getme '''
pass
def logOut(self):
''' See: https://core.telegram.org/bots/api#logout '''
pass
def close(self):
''' See: https://core.telegram.org/bots/api#close '''
pass
def sendMessage(self, chat_id: Union[int, str], text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendmessage '''
pass
def forwardMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
''' See: https://core.telegram.org/bots/api#forwardmessage '''
pass
def copyMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#copymessage '''
pass
def sendPhoto(self, chat_id: Union[int, str], photo,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendphoto
:param photo:
- string: ``file_id`` for a photo existing on Telegram servers
- string: HTTP URL of a photo from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (filename, file-like object).
'''
pass
def sendAudio(self, chat_id: Union[int, str], audio,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
performer=None,
title=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendaudio
:param audio: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def sendDocument(self, chat_id: Union[int, str], document,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_content_type_detection=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#senddocument
:param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def sendVideo(self, chat_id: Union[int, str], video,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
supports_streaming=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvideo
:param video: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def sendAnimation(self, chat_id: Union[int, str], animation,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendanimation
:param animation: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def sendVoice(self, chat_id: Union[int, str], voice,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvoice
:param voice: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def sendVideoNote(self, chat_id: Union[int, str], video_note,
duration=None,
length=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvideonote
:param video_note: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
:param length:
Although marked as optional, this method does not seem to work without
it being specified. Supply any integer you want. It seems to have no effect
on the video note's display size.
'''
pass
def sendMediaGroup(self, chat_id: Union[int, str], media,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None):
'''
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
:param media:
To indicate media locations, each InputMedia object's ``media`` field
should be one of these:
- string: ``file_id`` for a file existing on Telegram servers
- string: HTTP URL of a file from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (form-data name, file-like object)
- tuple: (form-data name, (filename, file-like object))
In case of uploading, you may supply customized multipart/form-data
names for each uploaded file (as in last 2 options above). Otherwise,
amanobot assigns unique names to each uploaded file. Names assigned by
amanobot will not collide with user-supplied names, if any.
'''
pass
def sendLocation(self, chat_id: Union[int, str], latitude, longitude,
horizontal_accuracy=None,
live_period=None,
heading=None,
proximity_alert_radius=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendlocation '''
pass
def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
horizontal_accuracy=None,
heading=None,
proximity_alert_radius=None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
'''
pass
def stopMessageLiveLocation(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#stopmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
'''
pass
def sendVenue(self, chat_id: Union[int, str], latitude, longitude, title, address,
foursquare_id=None,
foursquare_type=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendvenue '''
pass
def sendContact(self, chat_id: Union[int, str], phone_number, first_name,
last_name=None,
vcard=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendcontact '''
pass
def sendPoll(self, chat_id: Union[int, str], question, options,
is_anonymous=None,
type=None,
allows_multiple_answers=None,
correct_option_id=None,
explanation=None,
explanation_parse_mode: str = None,
open_period=None,
is_closed=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendpoll '''
pass
def sendDice(self, chat_id: Union[int, str],
emoji=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#senddice '''
pass
def sendGame(self, chat_id: Union[int, str], game_short_name,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendgame '''
pass
def sendInvoice(self, chat_id: Union[int, str], title, description, payload,
provider_token, start_parameter, currency, prices,
provider_data=None,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,
need_name=None,
need_phone_number=None,
need_email=None,
need_shipping_address=None,
is_flexible=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendinvoice '''
pass
def sendChatAction(self, chat_id: Union[int, str], action):
''' See: https://core.telegram.org/bots/api#sendchataction '''
pass
def getUserProfilePhotos(self, user_id,
offset=None,
limit=None):
''' See: https://core.telegram.org/bots/api#getuserprofilephotos '''
pass
def getFile(self, file_id):
''' See: https://core.telegram.org/bots/api#getfile '''
pass
def kickChatMember(self, chat_id: Union[int, str], user_id,
until_date: int = None,
revoke_messages: bool = None):
''' See: https://core.telegram.org/bots/api#kickchatmember '''
pass
def unbanChatMember(self, chat_id: Union[int, str], user_id,
only_if_banned=None):
''' See: https://core.telegram.org/bots/api#unbanchatmember '''
pass
def restrictChatMember(self, chat_id: Union[int, str], user_id,
until_date=None,
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
''' See: https://core.telegram.org/bots/api#restrictchatmember '''
pass
def promoteChatMember(self, chat_id: Union[int, str], user_id,
is_anonymous=None,
can_manage_chat=None,
can_post_messages=None,
can_edit_messages=None,
can_delete_messages=None,
can_manage_voice_chats=None,
can_restrict_members=None,
can_promote_members=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None):
''' See: https://core.telegram.org/bots/api#promotechatmember '''
pass
def setChatAdministratorCustomTitle(self, chat_id: Union[int, str], user_id,
custom_title):
''' See: https://core.telegram.org/bots/api#setchatadministratorcustomtitle '''
pass
def setChatPermissions(self, chat_id: Union[int, str],
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
''' See: https://core.telegram.org/bots/api#setchatpermissions '''
pass
def exportChatInviteLink(self, chat_id):
''' See: https://core.telegram.org/bots/api#exportchatinvitelink '''
pass
def createChatInviteLink(self, chat_id,
expire_date: int = None,
member_limit: int = None):
''' See: https://core.telegram.org/bots/api#createchatinvitelink '''
pass
def editChatInviteLink(self, chat_id,
invite_link: str,
expire_date: int = None,
member_limit: int = None):
''' See: https://core.telegram.org/bots/api#editchatinvitelink '''
pass
def revokeChatInviteLink(self, chat_id, invite_link: str):
''' See: https://core.telegram.org/bots/api#revokechatinvitelink '''
pass
def setChatPhoto(self, chat_id: Union[int, str], photo):
''' See: https://core.telegram.org/bots/api#setchatphoto '''
pass
def deleteChatPhoto(self, chat_id):
''' See: https://core.telegram.org/bots/api#deletechatphoto '''
pass
def setChatTitle(self, chat_id: Union[int, str], title):
''' See: https://core.telegram.org/bots/api#setchattitle '''
pass
def setChatDescription(self, chat_id: Union[int, str],
description=None):
''' See: https://core.telegram.org/bots/api#setchatdescription '''
pass
def pinChatMessage(self, chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
''' See: https://core.telegram.org/bots/api#pinchatmessage '''
pass
def unpinChatMessage(self, chat_id: Union[int, str],
message_id=None):
''' See: https://core.telegram.org/bots/api#unpinchatmessage '''
pass
def unpinAllChatMessages(self, chat_id):
''' See: https://core.telegram.org/bots/api#unpinallchatmessages '''
pass
def leaveChat(self, chat_id):
''' See: https://core.telegram.org/bots/api#leavechat '''
pass
def getChat(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchat '''
pass
def getChatAdministrators(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatadministrators '''
pass
def getChatMembersCount(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatmemberscount '''
pass
def getChatMembersCount(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatmember '''
pass
def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
''' See: https://core.telegram.org/bots/api#setchatstickerset '''
pass
def deleteChatStickerSet(self, chat_id):
''' See: https://core.telegram.org/bots/api#deletechatstickerset '''
pass
def answerCallbackQuery(self, callback_query_id,
text=None,
show_alert=None,
url=None,
cache_time=None):
''' See: https://core.telegram.org/bots/api#answercallbackquery '''
pass
def setMyCommands(self, commands=None):
''' See: https://core.telegram.org/bots/api#setmycommands '''
pass
def getMyCommands(self):
''' See: https://core.telegram.org/bots/api#getmycommands '''
pass
def setPassportDataErrors(self, user_id, errors):
''' See: https://core.telegram.org/bots/api#setpassportdataerrors '''
pass
def answerShippingQuery(self, shipping_query_id, ok,
shipping_options=None,
error_message=None):
''' See: https://core.telegram.org/bots/api#answershippingquery '''
pass
def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
''' See: https://core.telegram.org/bots/api#answerprecheckoutquery '''
pass
def editMessageText(self, msg_identifier, text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`amanobot.message_identifier`
'''
pass
def editMessageCaption(self, msg_identifier,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
'''
pass
def editMessageMedia(self, msg_identifier, media,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
'''
pass
def editMessageReplyMarkup(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagereplymarkup
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
'''
pass
def stopPoll(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``).
You may extract this value easily with :meth:`amanobot.message_identifier`
'''
pass
def deleteMessage(self, msg_identifier):
'''
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`,
except this method does not work on inline messages.
'''
pass
def sendSticker(self, chat_id: Union[int, str], sticker,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
'''
pass
def getStickerSet(self, name):
'''
See: https://core.telegram.org/bots/api#getstickerset
'''
pass
def uploadStickerFile(self, user_id, png_sticker):
'''
See: https://core.telegram.org/bots/api#uploadstickerfile
'''
pass
def createNewStickerSet(self, user_id, name, title, emojis,
png_sticker=None,
tgs_sticker=None,
contains_masks=None,
mask_position=None):
'''
See: https://core.telegram.org/bots/api#createnewstickerset
'''
pass
def addStickerToSet(self, user_id, name, emojis,
png_sticker=None,
tgs_sticker=None,
mask_position=None):
'''
See: https://core.telegram.org/bots/api#addstickertoset
'''
pass
def setStickerPositionInSet(self, sticker, position):
'''
See: https://core.telegram.org/bots/api#setstickerpositioninset
'''
pass
def deleteStickerFromSet(self, sticker):
'''
See: https://core.telegram.org/bots/api#deletestickerfromset
'''
pass
def setStickerSetThumb(self, name, user_id,
thumb=None):
'''
See: https://core.telegram.org/bots/api#setstickersetthumb
'''
pass
def answerInlineQuery(self, inline_query_id, results,
cache_time=None,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None):
''' See: https://core.telegram.org/bots/api#answerinlinequery '''
pass
def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None,
_raise_errors=None):
''' See: https://core.telegram.org/bots/api#getupdates '''
pass
def setWebhook(self,
url=None,
certificate=None,
ip_address=None,
max_connections=None,
allowed_updates=None,
drop_pending_updates=None):
''' See: https://core.telegram.org/bots/api#setwebhook '''
pass
def deleteWebhook(self,
drop_pending_updates=None):
pass
def getWebhookInfo(self):
''' See: https://core.telegram.org/bots/api#getwebhookinfo '''
pass
def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
'''
See: https://core.telegram.org/bots/api#setgamescore
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
'''
pass
def getGameHighScores(self, user_id, game_message_identifier):
'''
See: https://core.telegram.org/bots/api#getgamehighscores
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`amanobot.Bot.editMessageText`
'''
pass
def download_file(self, file_id, dest):
'''
Download a file to local disk.
:param dest: a path or a ``file`` object
'''
pass
def message_loop(self, callback=None, relax=0.1,
timeout=20, allowed_updates=None,
source=None, ordered=True, maxhold=3,
run_forever=False):
'''
:deprecated: will be removed in future. Use :class:`.MessageLoop` instead.
Spawn a thread to constantly ``getUpdates`` or pull updates from a queue.
Apply ``callback`` to every message received. Also starts the scheduler thread
for internal events.
:param callback:
a function that takes one argument (the message), or a routing table.
If ``None``, the bot's ``handle`` method is used.
A *routing table* is a dictionary of ``{flavor: function}``, mapping messages to appropriate
handler functions according to their flavors. It allows you to define functions specifically
to handle one flavor of messages. It usually looks like this: ``{'chat': fn1,
'callback_query': fn2, 'inline_query': fn3, ...}``. Each handler function should take
one argument (the message).
:param source:
Source of updates.
If ``None``, ``getUpdates`` is used to obtain new messages from Telegram servers.
If it is a synchronized queue, new messages are pulled from the queue.
A web application implementing a webhook can dump updates into the queue,
while the bot pulls from it. This is how amanobot can be integrated with webhooks.
Acceptable contents in queue:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
When ``source`` is ``None``, these parameters are meaningful:
:type relax: float
:param relax: seconds between each ``getUpdates``
:type timeout: int
:param timeout:
``timeout`` parameter supplied to :meth:`amanobot.Bot.getUpdates`,
controlling how long to poll.
:type allowed_updates: array of string
:param allowed_updates:
``allowed_updates`` parameter supplied to :meth:`amanobot.Bot.getUpdates`,
controlling which types of updates to receive.
When ``source`` is a queue, these parameters are meaningful:
:type ordered: bool
:param ordered:
If ``True``, ensure in-order delivery of messages to ``callback``
(i.e. updates with a smaller ``update_id`` always come before those with
a larger ``update_id``).
If ``False``, no re-ordering is done. ``callback`` is applied to messages
as soon as they are pulled from queue.
:type maxhold: float
:param maxhold:
Applied only when ``ordered`` is ``True``. The maximum number of seconds
an update is held waiting for a not-yet-arrived smaller ``update_id``.
When this number of seconds is up, the update is delivered to ``callback``
even if some smaller ``update_id``\s have not yet arrived. If those smaller
``update_id``\s arrive at some later time, they are discarded.
Finally, there is this parameter, meaningful always:
:type run_forever: bool or str
:param run_forever:
If ``True`` or any non-empty string, append an infinite loop at the end of
this method, so it never returns. Useful as the very last line in a program.
A non-empty string will also be printed, useful as an indication that the
program is listening.
'''
pass
def collector():
pass
def relay_to_collector(update):
pass
def get_from_telegram_server():
pass
def dictify(data):
pass
def get_from_queue_unordered(qu):
pass
def get_from_queue_unordered(qu):
pass
| 111 | 82 | 12 | 1 | 8 | 3 | 2 | 0.4 | 1 | 15 | 3 | 2 | 85 | 4 | 85 | 86 | 1,227 | 184 | 756 | 462 | 405 | 302 | 458 | 215 | 352 | 18 | 1 | 7 | 161 |
4,427 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/__init__.py
|
amanobot.DelegatorBot
|
class DelegatorBot(SpeakerBot):
def __init__(self, token, delegation_patterns):
"""
:param delegation_patterns: a list of (seeder, delegator) tuples.
"""
super(DelegatorBot, self).__init__(token)
self._delegate_records = [p + ({},) for p in delegation_patterns]
@staticmethod
def _startable(delegate):
return ((hasattr(delegate, 'start') and inspect.ismethod(delegate.start)) and
(hasattr(delegate, 'is_alive') and inspect.ismethod(delegate.is_alive)))
@staticmethod
def _tuple_is_valid(t):
return len(t) == 3 and callable(t[0]) and type(t[1]) in [list, tuple] and type(t[2]) is dict
def _ensure_startable(self, delegate):
if self._startable(delegate):
return delegate
if callable(delegate):
return threading.Thread(target=delegate)
if type(delegate) is tuple and self._tuple_is_valid(delegate):
func, args, kwargs = delegate
return threading.Thread(target=func, args=args, kwargs=kwargs)
raise RuntimeError(
'Delegate does not have the required methods, is not callable, and is not a valid tuple.')
def handle(self, msg):
self._mic.send(msg)
for calculate_seed, make_delegate, dict in self._delegate_records:
id = calculate_seed(msg)
if id is None:
continue
elif isinstance(id, collections.Hashable):
if id not in dict or not dict[id].is_alive():
d = make_delegate((self, msg, id))
d = self._ensure_startable(d)
dict[id] = d
dict[id].start()
else:
d = make_delegate((self, msg, id))
d = self._ensure_startable(d)
d.start()
|
class DelegatorBot(SpeakerBot):
def __init__(self, token, delegation_patterns):
'''
:param delegation_patterns: a list of (seeder, delegator) tuples.
'''
pass
@staticmethod
def _startable(delegate):
pass
@staticmethod
def _tuple_is_valid(t):
pass
def _ensure_startable(self, delegate):
pass
def handle(self, msg):
pass
| 8 | 1 | 8 | 1 | 7 | 1 | 2 | 0.08 | 1 | 7 | 0 | 1 | 3 | 1 | 5 | 94 | 47 | 7 | 37 | 12 | 29 | 3 | 31 | 10 | 25 | 5 | 3 | 3 | 12 |
4,428 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/event/alarm.py
|
alarm.AlarmSetter
|
class AlarmSetter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(AlarmSetter, self).__init__(*args, **kwargs)
# 1. Customize the routing table:
# On seeing an event of flavor `_alarm`, call `self.on__alarm`.
# To prevent flavors from colliding with those of Telegram messages,
# events are given flavors prefixed with `_` by convention. Also by
# convention is that the event-handling function is named `on_`
# followed by flavor, leading to the double underscore.
self.router.routing_table['_alarm'] = self.on__alarm
# 2. Define event-handling function
def on__alarm(self, event):
print(event) # see what the event object actually looks like
self.sender.sendMessage('Beep beep, time to wake up!')
def on_chat_message(self, msg):
try:
delay = float(msg['text'])
# 3. Schedule event
# The second argument is the event spec: a 2-tuple of (flavor, dict).
# Put any custom data in the dict. Retrieve them in the event-handling function.
self.scheduler.event_later(delay, ('_alarm', {'payload': delay}))
self.sender.sendMessage('Got it. Alarm is set at %.1f seconds from now.' % delay)
except ValueError:
self.sender.sendMessage('Not a number. No alarm set.')
|
class AlarmSetter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
def on__alarm(self, event):
pass
def on_chat_message(self, msg):
pass
| 4 | 0 | 8 | 1 | 4 | 3 | 1 | 0.79 | 1 | 3 | 0 | 0 | 3 | 0 | 3 | 20 | 28 | 4 | 14 | 5 | 10 | 11 | 14 | 5 | 10 | 2 | 3 | 1 | 4 |
4,429 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/guessa.py
|
guessa.Player
|
class Player(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(Player, self).__init__(*args, **kwargs)
self._answer = random.randint(0,99)
@staticmethod
def _hint(answer, guess):
if answer > guess:
return 'larger'
return 'smaller'
async def open(self, initial_msg, seed):
await self.sender.sendMessage('Guess my number')
return True # prevent on_message() from being called on the initial message
async def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type != 'text':
await self.sender.sendMessage('Give me a number, please.')
return
try:
guess = int(msg['text'])
except ValueError:
await self.sender.sendMessage('Give me a number, please.')
return
# check the guess against the answer ...
if guess != self._answer:
# give a descriptive hint
hint = self._hint(self._answer, guess)
await self.sender.sendMessage(hint)
else:
await self.sender.sendMessage('Correct!')
self.close()
async def on__idle(self, event):
await self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
self.close()
|
class Player(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
@staticmethod
def _hint(answer, guess):
pass
async def open(self, initial_msg, seed):
pass
async def on_chat_message(self, msg):
pass
async def on__idle(self, event):
pass
| 7 | 0 | 7 | 1 | 6 | 1 | 2 | 0.1 | 1 | 3 | 0 | 0 | 4 | 1 | 5 | 22 | 40 | 7 | 31 | 11 | 24 | 3 | 29 | 10 | 23 | 4 | 3 | 1 | 9 |
4,430 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.InterceptCallbackQueryMixin
|
class InterceptCallbackQueryMixin():
"""
Install a :class:`.CallbackQueryCoordinator` to capture callback query
dynamically.
Using this mixin has one consequence. The :meth:`self.bot` property no longer
returns the original :class:`.Bot` object. Instead, it returns an augmented
version of the :class:`.Bot` (augmented by :class:`.CallbackQueryCoordinator`).
The original :class:`.Bot` can be accessed with ``self.__bot`` (double underscore).
"""
CallbackQueryCoordinator = CallbackQueryCoordinator
def __init__(self, intercept_callback_query, *args, **kwargs):
"""
:param intercept_callback_query:
a 2-tuple (enable_chat, enable_inline) to pass to
:class:`.CallbackQueryCoordinator`
"""
global _cqc_origins
# Restore origin set to CallbackQueryCoordinator
if self.id in _cqc_origins:
origin_set = _cqc_origins[self.id]
else:
origin_set = set()
_cqc_origins[self.id] = origin_set
if isinstance(intercept_callback_query, tuple):
cqc_enable = intercept_callback_query
else:
cqc_enable = (intercept_callback_query,) * 2
self._callback_query_coordinator = self.CallbackQueryCoordinator(self.id, origin_set, *cqc_enable)
cqc = self._callback_query_coordinator
cqc.configure(self.listener)
self.__bot = self._bot # keep original version of bot
self._bot = cqc.augment_bot(self._bot) # modify send* and edit* methods
self.on_message = cqc.augment_on_message(self.on_message) # modify on_message()
super(InterceptCallbackQueryMixin, self).__init__(*args, **kwargs)
def __del__(self):
global _cqc_origins
if self.id in _cqc_origins and not _cqc_origins[self.id]:
del _cqc_origins[self.id]
# Remove empty set from dictionary
@property
def callback_query_coordinator(self):
return self._callback_query_coordinator
|
class InterceptCallbackQueryMixin():
'''
Install a :class:`.CallbackQueryCoordinator` to capture callback query
dynamically.
Using this mixin has one consequence. The :meth:`self.bot` property no longer
returns the original :class:`.Bot` object. Instead, it returns an augmented
version of the :class:`.Bot` (augmented by :class:`.CallbackQueryCoordinator`).
The original :class:`.Bot` can be accessed with ``self.__bot`` (double underscore).
'''
def __init__(self, intercept_callback_query, *args, **kwargs):
'''
:param intercept_callback_query:
a 2-tuple (enable_chat, enable_inline) to pass to
:class:`.CallbackQueryCoordinator`
'''
pass
def __del__(self):
pass
@property
def callback_query_coordinator(self):
pass
| 5 | 2 | 12 | 2 | 8 | 3 | 2 | 0.67 | 0 | 3 | 0 | 2 | 3 | 5 | 3 | 3 | 51 | 9 | 27 | 16 | 20 | 18 | 24 | 14 | 18 | 3 | 0 | 1 | 6 |
4,431 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.IdleTerminateMixin
|
class IdleTerminateMixin():
"""
Install an :class:`.IdleEventCoordinator` to manage idle timeout. Also define
instance method ``on__idle()`` to handle idle timeout events.
"""
IdleEventCoordinator = IdleEventCoordinator
def __init__(self, timeout, *args, **kwargs):
self._idle_event_coordinator = self.IdleEventCoordinator(self.scheduler, timeout)
idlec = self._idle_event_coordinator
idlec.refresh() # start timer
self.on_message = idlec.augment_on_message(self.on_message)
self.on_close = idlec.augment_on_close(self.on_close)
super(IdleTerminateMixin, self).__init__(*args, **kwargs)
@property
def idle_event_coordinator(self):
return self._idle_event_coordinator
@staticmethod
def on__idle(event):
"""
Raise an :class:`.IdleTerminate` to close the delegate.
"""
raise exception.IdleTerminate(event['_idle']['seconds'])
|
class IdleTerminateMixin():
'''
Install an :class:`.IdleEventCoordinator` to manage idle timeout. Also define
instance method ``on__idle()`` to handle idle timeout events.
'''
def __init__(self, timeout, *args, **kwargs):
pass
@property
def idle_event_coordinator(self):
pass
@staticmethod
def on__idle(event):
'''
Raise an :class:`.IdleTerminate` to close the delegate.
'''
pass
| 6 | 2 | 5 | 0 | 4 | 1 | 1 | 0.53 | 0 | 2 | 1 | 5 | 2 | 3 | 3 | 3 | 25 | 3 | 15 | 11 | 9 | 8 | 13 | 9 | 9 | 1 | 0 | 0 | 3 |
4,432 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/guess.py
|
guess.Player
|
class Player(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(Player, self).__init__(*args, **kwargs)
self._answer = random.randint(0,99)
@staticmethod
def _hint(answer, guess):
if answer > guess:
return 'larger'
return 'smaller'
def open(self, initial_msg, seed):
self.sender.sendMessage('Guess my number')
return True # prevent on_message() from being called on the initial message
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type != 'text':
self.sender.sendMessage('Give me a number, please.')
return
try:
guess = int(msg['text'])
except ValueError:
self.sender.sendMessage('Give me a number, please.')
return
# check the guess against the answer ...
if guess != self._answer:
# give a descriptive hint
hint = self._hint(self._answer, guess)
self.sender.sendMessage(hint)
else:
self.sender.sendMessage('Correct!')
self.close()
def on__idle(self, event):
self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
self.close()
|
class Player(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
@staticmethod
def _hint(answer, guess):
pass
def open(self, initial_msg, seed):
pass
def on_chat_message(self, msg):
pass
def on__idle(self, event):
pass
| 7 | 0 | 7 | 1 | 6 | 1 | 2 | 0.1 | 1 | 3 | 0 | 0 | 4 | 1 | 5 | 22 | 40 | 7 | 31 | 11 | 24 | 3 | 29 | 10 | 23 | 4 | 3 | 1 | 9 |
4,433 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/webhook/flask_counter.py
|
flask_counter.MessageCounter
|
class MessageCounter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(MessageCounter, self).__init__(*args, **kwargs)
self._count = 0
def on_chat_message(self, msg):
self._count += 1
self.sender.sendMessage(self._count)
|
class MessageCounter(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
def on_chat_message(self, msg):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 19 | 8 | 1 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
4,434 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/datecalca.py
|
datecalca.DateCalculator
|
class DateCalculator(InlineUserHandler,
AnswererMixin,
InterceptCallbackQueryMixin):
def __init__(self, *args, **kwargs):
super(DateCalculator, self).__init__(*args, **kwargs)
global user_ballots
if self.id in user_ballots:
self._ballots = user_ballots[self.id]
print('Ballot retrieved.')
else:
self._ballots = {}
print('Ballot initialized.')
self.router.routing_table['_expired'] = self.on__expired
def on_inline_query(self, msg):
def compute():
query_id, from_id, query_string = glance(msg, flavor='inline_query')
print('Inline query:', query_id, from_id, query_string)
weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
query_string = query_string.lower()
query_weekdays = [day[0] for day in enumerate(weekdays) if day[1].startswith(query_string)]
def days_to(today, target):
d = target - today
if d <= 0:
d += 7
return timedelta(days=d)
today = datetime.today()
deltas = [days_to(today.weekday(), target) for target in query_weekdays]
def make_result(today, week_delta, day_delta):
future = today + week_delta + day_delta
n = 0 if future.weekday() > today.weekday() else 1
n += int(week_delta.days / 7)
return InlineQueryResultArticle(
id=future.strftime('%Y-%m-%d'),
title=('next '*n if n > 0 else 'this ') + weekdays[future.weekday()].capitalize(),
input_message_content=InputTextMessageContent(
message_text=future.strftime('%A, %Y-%m-%d')
),
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[
InlineKeyboardButton(text='Yes', callback_data='yes'),
InlineKeyboardButton(text='No', callback_data='no'),
]]
)
)
results = []
for i in range(0,3):
weeks = timedelta(weeks=i)
for d in deltas:
results.append(make_result(today, weeks, d))
return results
self.answerer.answer(msg, compute)
def on_chosen_inline_result(self, msg):
if 'inline_message_id' in msg:
inline_message_id = msg['inline_message_id']
suggested_date = msg['result_id']
self._ballots[inline_message_id] = {}
self.scheduler.event_later(30, ('_expired', {'seconds': 30,
'inline_message_id': inline_message_id,
'date': suggested_date}))
async def on_callback_query(self, msg):
if 'inline_message_id' in msg:
inline_message_id = msg['inline_message_id']
ballot = self._ballots[inline_message_id]
query_id, from_id, query_data = glance(msg, flavor='callback_query')
if from_id in ballot:
await self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % ballot[from_id])
else:
await self.bot.answerCallbackQuery(query_id, text='Ok')
ballot[from_id] = query_data
@staticmethod
def _count(ballot):
yes = reduce(lambda a,b: a+(1 if b=='yes' else 0), ballot.values(), 0)
no = reduce(lambda a,b: a+(1 if b=='no' else 0), ballot.values(), 0)
return yes, no
async def on__expired(self, event):
evt = peel(event)
inline_message_id = evt['inline_message_id']
suggested_date = evt['date']
ballot = self._ballots[inline_message_id]
text = '%s\nYes: %d\nNo: %d' % ((suggested_date,) + self._count(ballot))
editor = Editor(self.bot, inline_message_id)
await editor.editMessageText(text=text, reply_markup=None)
del self._ballots[inline_message_id]
self.close()
def on_close(self, ex):
global user_ballots
user_ballots[self.id] = self._ballots
print('Closing, ballots saved.')
|
class DateCalculator(InlineUserHandler,
AnswererMixin,
InterceptCallbackQueryMixin):
def __init__(self, *args, **kwargs):
pass
def on_inline_query(self, msg):
pass
def compute():
pass
def days_to(today, target):
pass
def make_result(today, week_delta, day_delta):
pass
def on_chosen_inline_result(self, msg):
pass
async def on_callback_query(self, msg):
pass
@staticmethod
def _count(ballot):
pass
async def on__expired(self, event):
pass
def on_close(self, ex):
pass
| 12 | 0 | 17 | 3 | 14 | 0 | 2 | 0 | 3 | 7 | 1 | 0 | 6 | 2 | 7 | 29 | 110 | 22 | 88 | 43 | 72 | 0 | 69 | 39 | 56 | 3 | 4 | 2 | 19 |
4,435 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/countera.py
|
countera.MessageCounter
|
class MessageCounter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(MessageCounter, self).__init__(*args, **kwargs)
self._count = 0
async def on_chat_message(self, msg):
self._count += 1
await self.sender.sendMessage(self._count)
|
class MessageCounter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
async def on_chat_message(self, msg):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 19 | 8 | 1 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
4,436 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/countera.py
|
countera.MessageCounter
|
class MessageCounter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(MessageCounter, self).__init__(*args, **kwargs)
self._count = 0
async def on_chat_message(self, msg):
self._count += 1
await self.sender.sendMessage(self._count)
|
class MessageCounter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
async def on_chat_message(self, msg):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 19 | 8 | 1 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
4,437 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatboxa_nodb.py
|
chatboxa_nodb.UnreadStore
|
class UnreadStore():
def __init__(self):
self._db = {}
def put(self, msg):
chat_id = msg['chat']['id']
if chat_id not in self._db:
self._db[chat_id] = []
self._db[chat_id].append(msg)
# Pull all unread messages of a `chat_id`
def pull(self, chat_id):
messages = self._db[chat_id]
del self._db[chat_id]
# sort by date
messages.sort(key=lambda m: m['date'])
return messages
# Tells how many unread messages per chat_id
def unread_per_chat(self):
return [(k,len(v)) for k,v in self._db.items()]
|
class UnreadStore():
def __init__(self):
pass
def put(self, msg):
pass
def pull(self, chat_id):
pass
def unread_per_chat(self):
pass
| 5 | 0 | 5 | 1 | 4 | 0 | 1 | 0.2 | 0 | 0 | 0 | 0 | 4 | 1 | 4 | 4 | 24 | 6 | 15 | 8 | 10 | 3 | 15 | 8 | 10 | 2 | 0 | 1 | 5 |
4,438 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatboxa_nodb.py
|
chatboxa_nodb.OwnerHandler
|
class OwnerHandler(amanobot.aio.helper.ChatHandler):
def __init__(self, seed_tuple, store, **kwargs):
super(OwnerHandler, self).__init__(seed_tuple, **kwargs)
self._store = store
async def _read_messages(self, messages):
for msg in messages:
# assume all messages are text
await self.sender.sendMessage(msg['text'])
async def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type != 'text':
await self.sender.sendMessage("I don't understand")
return
command = msg['text'].strip().lower()
# Tells who has sent you how many messages
if command == '/unread':
results = self._store.unread_per_chat()
lines = []
for r in results:
n = 'ID: %d\n%d unread' % r
lines.append(n)
if not len(lines):
await self.sender.sendMessage('No unread messages')
else:
await self.sender.sendMessage('\n'.join(lines))
# read next sender's messages
elif command == '/next':
results = self._store.unread_per_chat()
if not len(results):
await self.sender.sendMessage('No unread messages')
return
chat_id = results[0][0]
unread_messages = self._store.pull(chat_id)
await self.sender.sendMessage('From ID: %d' % chat_id)
await self._read_messages(unread_messages)
else:
await self.sender.sendMessage("I don't understand")
|
class OwnerHandler(amanobot.aio.helper.ChatHandler):
def __init__(self, seed_tuple, store, **kwargs):
pass
async def _read_messages(self, messages):
pass
async def on_chat_message(self, msg):
pass
| 4 | 0 | 15 | 3 | 11 | 1 | 3 | 0.09 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 20 | 49 | 12 | 34 | 13 | 30 | 3 | 31 | 13 | 27 | 7 | 3 | 2 | 10 |
4,439 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/event/alarma.py
|
alarma.AlarmSetter
|
class AlarmSetter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(AlarmSetter, self).__init__(*args, **kwargs)
# 1. Customize the routing table:
# On seeing an event of flavor `_alarm`, call `self.on__alarm`.
# To prevent flavors from colliding with those of Telegram messages,
# events are given flavors prefixed with `_` by convention. Also by
# convention is that the event-handling function is named `on_`
# followed by flavor, leading to the double underscore.
self.router.routing_table['_alarm'] = self.on__alarm
# 2. Define event-handling function
async def on__alarm(self, event):
print(event) # see what the event object actually looks like
await self.sender.sendMessage('Beep beep, time to wake up!')
async def on_chat_message(self, msg):
try:
delay = float(msg['text'])
# 3. Schedule event
# The second argument is the event spec: a 2-tuple of (flavor, dict).
# Put any custom data in the dict. Retrieve them in the event-handling function.
self.scheduler.event_later(delay, ('_alarm', {'payload': delay}))
await self.sender.sendMessage('Got it. Alarm is set at %.1f seconds from now.' % delay)
except ValueError:
await self.sender.sendMessage('Not a number. No alarm set.')
|
class AlarmSetter(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
async def on__alarm(self, event):
pass
async def on_chat_message(self, msg):
pass
| 4 | 0 | 8 | 1 | 4 | 3 | 1 | 0.79 | 1 | 3 | 0 | 0 | 3 | 0 | 3 | 20 | 28 | 4 | 14 | 5 | 10 | 11 | 14 | 5 | 10 | 2 | 3 | 1 | 4 |
4,440 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/datecalc.py
|
datecalc.DateCalculator
|
class DateCalculator(amanobot.helper.InlineUserHandler,
amanobot.helper.AnswererMixin,
amanobot.helper.InterceptCallbackQueryMixin):
def __init__(self, *args, **kwargs):
super(DateCalculator, self).__init__(*args, **kwargs)
global user_ballots
if self.id in user_ballots:
self._ballots = user_ballots[self.id]
print('Ballot retrieved.')
else:
self._ballots = {}
print('Ballot initialized.')
self.router.routing_table['_expired'] = self.on__expired
def on_inline_query(self, msg):
def compute():
query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query')
print('Inline query:', query_id, from_id, query_string)
weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
query_string = query_string.lower()
query_weekdays = [day[0] for day in enumerate(weekdays) if day[1].startswith(query_string)]
def days_to(today, target):
d = target - today
if d <= 0:
d += 7
return timedelta(days=d)
today = datetime.today()
deltas = [days_to(today.weekday(), target) for target in query_weekdays]
def make_result(today, week_delta, day_delta):
future = today + week_delta + day_delta
n = 0 if future.weekday() > today.weekday() else 1
n += int(week_delta.days / 7)
return InlineQueryResultArticle(
id=future.strftime('%Y-%m-%d'),
title=('next '*n if n > 0 else 'this ') + weekdays[future.weekday()].capitalize(),
input_message_content=InputTextMessageContent(
message_text=future.strftime('%A, %Y-%m-%d')
),
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[
InlineKeyboardButton(text='Yes', callback_data='yes'),
InlineKeyboardButton(text='No', callback_data='no'),
]]
)
)
results = []
for i in range(0,3):
weeks = timedelta(weeks=i)
for d in deltas:
results.append(make_result(today, weeks, d))
return results
self.answerer.answer(msg, compute)
def on_chosen_inline_result(self, msg):
if 'inline_message_id' in msg:
inline_message_id = msg['inline_message_id']
suggested_date = msg['result_id']
self._ballots[inline_message_id] = {}
self.scheduler.event_later(30, ('_expired', {'seconds': 30,
'inline_message_id': inline_message_id,
'date': suggested_date}))
def on_callback_query(self, msg):
if 'inline_message_id' in msg:
inline_message_id = msg['inline_message_id']
ballot = self._ballots[inline_message_id]
query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')
if from_id in ballot:
self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % ballot[from_id])
else:
self.bot.answerCallbackQuery(query_id, text='Ok')
ballot[from_id] = query_data
@staticmethod
def _count(ballot):
yes = reduce(lambda a,b: a+(1 if b=='yes' else 0), ballot.values(), 0)
no = reduce(lambda a,b: a+(1 if b=='no' else 0), ballot.values(), 0)
return yes, no
def on__expired(self, event):
evt = amanobot.peel(event)
inline_message_id = evt['inline_message_id']
suggested_date = evt['date']
ballot = self._ballots[inline_message_id]
text = '%s\nYes: %d\nNo: %d' % ((suggested_date,) + self._count(ballot))
editor = amanobot.helper.Editor(self.bot, inline_message_id)
editor.editMessageText(text=text, reply_markup=None)
del self._ballots[inline_message_id]
self.close()
def on_close(self, ex):
global user_ballots
user_ballots[self.id] = self._ballots
print('Closing, ballots saved.')
|
class DateCalculator(amanobot.helper.InlineUserHandler,
amanobot.helper.AnswererMixin,
amanobot.helper.InterceptCallbackQueryMixin):
def __init__(self, *args, **kwargs):
pass
def on_inline_query(self, msg):
pass
def compute():
pass
def days_to(today, target):
pass
def make_result(today, week_delta, day_delta):
pass
def on_chosen_inline_result(self, msg):
pass
def on_callback_query(self, msg):
pass
@staticmethod
def _count(ballot):
pass
def on__expired(self, event):
pass
def on_close(self, ex):
pass
| 12 | 0 | 17 | 3 | 14 | 0 | 2 | 0 | 3 | 7 | 1 | 0 | 6 | 2 | 7 | 29 | 110 | 22 | 88 | 43 | 72 | 0 | 69 | 39 | 56 | 3 | 4 | 2 | 19 |
4,441 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.EventNotFound
|
class EventNotFound(AmanobotException):
@property
def event(self):
return self.args[0]
|
class EventNotFound(AmanobotException):
@property
def event(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 5 | 1 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
4,442 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Answerer
|
class Answerer():
"""
When processing inline queries, ensure **at most one active thread** per user id.
"""
def __init__(self, bot):
self._bot = bot
self._workers = {} # map: user id --> worker thread
self._lock = threading.Lock() # control access to `self._workers`
def answer(outerself, inline_query, compute_fn, *compute_args, **compute_kwargs):
"""
Spawns a thread that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding thread is already working for a user, that thread is cancelled,
thus ensuring at most one active thread per user id.
:param inline_query:
The inline query to be processed. The originating user is inferred from ``msg['from']['id']``.
:param compute_fn:
A **thread-safe** function whose returned value is given to :meth:`.Bot.answerInlineQuery` to send.
May return:
- a *list* of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_
- a *tuple* whose first element is a list of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_,
followed by positional arguments to be supplied to :meth:`.Bot.answerInlineQuery`
- a *dictionary* representing keyword arguments to be supplied to :meth:`.Bot.answerInlineQuery`
:param \*compute_args: positional arguments to ``compute_fn``
:param \*\*compute_kwargs: keyword arguments to ``compute_fn``
"""
from_id = inline_query['from']['id']
class Worker(threading.Thread):
def __init__(innerself):
super(Worker, innerself).__init__()
innerself._cancelled = False
def cancel(innerself):
innerself._cancelled = True
def run(innerself):
try:
query_id = inline_query['id']
if innerself._cancelled:
return
# Important: compute function must be thread-safe.
ans = compute_fn(*compute_args, **compute_kwargs)
if innerself._cancelled:
return
if isinstance(ans, list):
outerself._bot.answerInlineQuery(query_id, ans)
elif isinstance(ans, tuple):
outerself._bot.answerInlineQuery(query_id, *ans)
elif isinstance(ans, dict):
outerself._bot.answerInlineQuery(query_id, **ans)
else:
raise ValueError('Invalid answer format')
finally:
with outerself._lock:
# Delete only if I have NOT been cancelled.
if not innerself._cancelled:
del outerself._workers[from_id]
# If I have been cancelled, that position in `outerself._workers`
# no longer belongs to me. I should not delete that key.
# Several threads may access `outerself._workers`. Use `outerself._lock` to protect.
with outerself._lock:
if from_id in outerself._workers:
outerself._workers[from_id].cancel()
outerself._workers[from_id] = Worker()
outerself._workers[from_id].start()
|
class Answerer():
'''
When processing inline queries, ensure **at most one active thread** per user id.
'''
def __init__(self, bot):
pass
def answer(outerself, inline_query, compute_fn, *compute_args, **compute_kwargs):
'''
Spawns a thread that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding thread is already working for a user, that thread is cancelled,
thus ensuring at most one active thread per user id.
:param inline_query:
The inline query to be processed. The originating user is inferred from ``msg['from']['id']``.
:param compute_fn:
A **thread-safe** function whose returned value is given to :meth:`.Bot.answerInlineQuery` to send.
May return:
- a *list* of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_
- a *tuple* whose first element is a list of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_,
followed by positional arguments to be supplied to :meth:`.Bot.answerInlineQuery`
- a *dictionary* representing keyword arguments to be supplied to :meth:`.Bot.answerInlineQuery`
:param \*compute_args: positional arguments to ``compute_fn``
:param \*\*compute_kwargs: keyword arguments to ``compute_fn``
'''
pass
class Worker(threading.Thread):
def __init__(self, bot):
pass
def cancel(innerself):
pass
def run(innerself):
pass
| 7 | 2 | 21 | 4 | 12 | 5 | 2 | 0.74 | 0 | 1 | 1 | 0 | 2 | 3 | 2 | 2 | 81 | 17 | 38 | 13 | 31 | 28 | 34 | 13 | 27 | 7 | 0 | 3 | 12 |
4,443 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/lovera.py
|
lovera.Lover
|
class Lover(amanobot.aio.helper.ChatHandler):
keyboard = InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text='Yes', callback_data='yes'),
InlineKeyboardButton(text='um ...', callback_data='no'),
]])
def __init__(self, *args, **kwargs):
super(Lover, self).__init__(*args, **kwargs)
# Retrieve from database
global propose_records
if self.id in propose_records:
self._count, self._edit_msg_ident = propose_records[self.id]
self._editor = amanobot.aio.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None
else:
self._count = 0
self._edit_msg_ident = None
self._editor = None
async def _propose(self):
self._count += 1
sent = await self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self.keyboard)
self._editor = amanobot.aio.helper.Editor(self.bot, sent)
self._edit_msg_ident = message_identifier(sent)
async def _cancel_last(self):
if self._editor:
await self._editor.editMessageReplyMarkup(reply_markup=None)
self._editor = None
self._edit_msg_ident = None
async def on_chat_message(self, msg):
await self._propose()
async def on_callback_query(self, msg):
query_id, from_id, query_data = glance(msg, flavor='callback_query')
if query_data == 'yes':
await self._cancel_last()
await self.sender.sendMessage('Thank you!')
self.close()
else:
await self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
await self._cancel_last()
await self._propose()
async def on__idle(self, event):
await self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
self.close()
def on_close(self, ex):
# Save to database
global propose_records
propose_records[self.id] = (self._count, self._edit_msg_ident)
|
class Lover(amanobot.aio.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
async def _propose(self):
pass
async def _cancel_last(self):
pass
async def on_chat_message(self, msg):
pass
async def on_callback_query(self, msg):
pass
async def on__idle(self, event):
pass
def on_close(self, ex):
pass
| 8 | 0 | 6 | 0 | 5 | 0 | 2 | 0.05 | 1 | 2 | 1 | 0 | 7 | 4 | 7 | 24 | 54 | 9 | 43 | 16 | 33 | 2 | 38 | 15 | 28 | 3 | 3 | 1 | 11 |
4,444 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/loop.py
|
amanobot.aio.loop.OrderedWebhook
|
class OrderedWebhook():
def __init__(self, bot, handle=None):
self._bot = bot
self._handle = _infer_handler_function(bot, handle)
self._update_queue = asyncio.Queue(loop=bot.loop)
async def run_forever(self, maxhold=3):
self._bot.scheduler.on_event(self._handle)
def extract_handle(update):
try:
self._handle(_extract_message(update)[1])
except:
# Localize the error so message thread can keep going.
traceback.print_exc()
finally:
return update['update_id']
# Here is the re-ordering mechanism, ensuring in-order delivery of updates.
max_id = None # max update_id passed to callback
buffer = collections.deque() # keep those updates which skip some update_id
qwait = None # how long to wait for updates,
# because buffer's content has to be returned in time.
while 1:
try:
update = await asyncio.wait_for(self._update_queue.get(), qwait)
if max_id is None:
# First message received, handle regardless.
max_id = extract_handle(update)
elif update['update_id'] == max_id + 1:
# No update_id skipped, handle naturally.
max_id = extract_handle(update)
# clear contagious updates in buffer
if len(buffer) > 0:
buffer.popleft() # first element belongs to update just received, useless now.
while 1:
try:
if type(buffer[0]) is dict:
max_id = extract_handle(buffer.popleft()) # updates that arrived earlier, handle them.
else:
break # gap, no more contagious updates
except IndexError:
break # buffer empty
elif update['update_id'] > max_id + 1:
# Update arrives pre-maturely, insert to buffer.
nbuf = len(buffer)
if update['update_id'] <= max_id + nbuf:
# buffer long enough, put update at position
buffer[update['update_id'] - max_id - 1] = update
else:
# buffer too short, lengthen it
expire = time.time() + maxhold
for a in range(nbuf, update['update_id']-max_id-1):
buffer.append(expire) # put expiry time in gaps
buffer.append(update)
else:
pass # discard
except asyncio.TimeoutError:
# debug message
# print('Timeout')
# some buffer contents have to be handled
# flush buffer until a non-expired time is encountered
while 1:
try:
if type(buffer[0]) is dict:
max_id = extract_handle(buffer.popleft())
else:
expire = buffer[0]
if expire <= time.time():
max_id += 1
buffer.popleft()
else:
break # non-expired
except IndexError:
break # buffer empty
except:
traceback.print_exc()
finally:
try:
# don't wait longer than next expiry time
qwait = buffer[0] - time.time()
qwait = max(qwait, 0)
except IndexError:
# buffer empty, can wait forever
qwait = None
# debug message
# print ('Buffer:', str(buffer), ', To Wait:', qwait, ', Max ID:', max_id)
def feed(self, data):
update = _dictify(data)
self._update_queue.put_nowait(update)
|
class OrderedWebhook():
def __init__(self, bot, handle=None):
pass
async def run_forever(self, maxhold=3):
pass
def extract_handle(update):
pass
def feed(self, data):
pass
| 5 | 0 | 26 | 3 | 19 | 7 | 6 | 0.4 | 0 | 5 | 0 | 0 | 3 | 3 | 3 | 3 | 100 | 13 | 70 | 16 | 65 | 28 | 61 | 16 | 56 | 18 | 0 | 7 | 22 |
4,445 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.WaitTooLong
|
class WaitTooLong(AmanobotException):
@property
def seconds(self):
return self.args[0]
|
class WaitTooLong(AmanobotException):
@property
def seconds(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 11 | 5 | 1 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
4,446 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.TelegramError
|
class TelegramError(AmanobotException):
"""
To indicate erroneous situations, Telegram returns a JSON object containing
an *error code* and a *description*. This will cause a ``TelegramError`` to
be raised. Before raising a generic ``TelegramError``, amanobot looks for
a more specific subclass that "matches" the error. If such a class exists,
an exception of that specific subclass is raised. This allows you to either
catch specific errors or to cast a wide net (by a catch-all ``TelegramError``).
This also allows you to incorporate custom ``TelegramError`` easily.
Subclasses must define a class variable ``DESCRIPTION_PATTERNS`` which is a list
of regular expressions. If an error's *description* matches any of the regular expressions,
an exception of that subclass is raised.
"""
@property
def description(self):
return self.args[0]
@property
def error_code(self):
return self.args[1]
@property
def json(self):
return self.args[2]
|
class TelegramError(AmanobotException):
'''
To indicate erroneous situations, Telegram returns a JSON object containing
an *error code* and a *description*. This will cause a ``TelegramError`` to
be raised. Before raising a generic ``TelegramError``, amanobot looks for
a more specific subclass that "matches" the error. If such a class exists,
an exception of that specific subclass is raised. This allows you to either
catch specific errors or to cast a wide net (by a catch-all ``TelegramError``).
This also allows you to incorporate custom ``TelegramError`` easily.
Subclasses must define a class variable ``DESCRIPTION_PATTERNS`` which is a list
of regular expressions. If an error's *description* matches any of the regular expressions,
an exception of that subclass is raised.
'''
@property
def description(self):
pass
@property
def error_code(self):
pass
@property
def json(self):
pass
| 7 | 1 | 2 | 0 | 2 | 0 | 1 | 1.2 | 1 | 0 | 0 | 6 | 3 | 0 | 3 | 13 | 26 | 4 | 10 | 7 | 3 | 12 | 7 | 4 | 3 | 1 | 4 | 0 | 3 |
4,447 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatbox_nodb.py
|
chatbox_nodb.OwnerHandler
|
class OwnerHandler(amanobot.helper.ChatHandler):
def __init__(self, seed_tuple, store, **kwargs):
super(OwnerHandler, self).__init__(seed_tuple, **kwargs)
self._store = store
def _read_messages(self, messages):
for msg in messages:
# assume all messages are text
self.sender.sendMessage(msg['text'])
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type != 'text':
self.sender.sendMessage("I don't understand")
return
command = msg['text'].strip().lower()
# Tells who has sent you how many messages
if command == '/unread':
results = self._store.unread_per_chat()
lines = []
for r in results:
n = 'ID: %d\n%d unread' % r
lines.append(n)
if not len(lines):
self.sender.sendMessage('No unread messages')
else:
self.sender.sendMessage('\n'.join(lines))
# read next sender's messages
elif command == '/next':
results = self._store.unread_per_chat()
if not len(results):
self.sender.sendMessage('No unread messages')
return
chat_id = results[0][0]
unread_messages = self._store.pull(chat_id)
self.sender.sendMessage('From ID: %d' % chat_id)
self._read_messages(unread_messages)
else:
self.sender.sendMessage("I don't understand")
|
class OwnerHandler(amanobot.helper.ChatHandler):
def __init__(self, seed_tuple, store, **kwargs):
pass
def _read_messages(self, messages):
pass
def on_chat_message(self, msg):
pass
| 4 | 0 | 15 | 3 | 11 | 1 | 3 | 0.09 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 20 | 49 | 12 | 34 | 13 | 30 | 3 | 31 | 13 | 27 | 7 | 3 | 2 | 10 |
4,448 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.BadFlavor
|
class BadFlavor(AmanobotException):
@property
def offender(self):
return self.args[0]
|
class BadFlavor(AmanobotException):
@property
def offender(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 5 | 1 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
4,449 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/inline/inline.py
|
inline.InlineHandler
|
class InlineHandler(amanobot.helper.InlineUserHandler, amanobot.helper.AnswererMixin):
def on_inline_query(self, msg):
def compute_answer():
query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query')
print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)
articles = [{'type': 'article',
'id': 'abc', 'title': query_string, 'message_text': query_string}]
return articles
self.answerer.answer(msg, compute_answer)
def on_chosen_inline_result(self, msg):
from pprint import pprint
pprint(msg)
result_id, from_id, query_string = amanobot.glance(msg, flavor='chosen_inline_result')
print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
|
class InlineHandler(amanobot.helper.InlineUserHandler, amanobot.helper.AnswererMixin):
def on_inline_query(self, msg):
pass
def compute_answer():
pass
def on_chosen_inline_result(self, msg):
pass
| 4 | 0 | 8 | 2 | 6 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 2 | 0 | 2 | 21 | 19 | 5 | 14 | 8 | 9 | 0 | 13 | 8 | 8 | 1 | 4 | 0 | 3 |
4,450 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/doc/_code/inline_per_user.py
|
inline_per_user.QueryCounter
|
class QueryCounter(amanobot.helper.InlineUserHandler, amanobot.helper.AnswererMixin):
def __init__(self, *args, **kwargs):
super(QueryCounter, self).__init__(*args, **kwargs)
self._count = 0
def on_inline_query(self, msg):
def compute():
query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query')
print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)
self._count += 1
text = '%d. %s' % (self._count, query_string)
articles = [InlineQueryResultArticle(
id='abc',
title=text,
input_message_content=InputTextMessageContent(
message_text=text
)
)]
return articles
self.answerer.answer(msg, compute)
def on_chosen_inline_result(self, msg):
result_id, from_id, query_string = amanobot.glance(msg, flavor='chosen_inline_result')
print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
|
class QueryCounter(amanobot.helper.InlineUserHandler, amanobot.helper.AnswererMixin):
def __init__(self, *args, **kwargs):
pass
def on_inline_query(self, msg):
pass
def compute():
pass
def on_chosen_inline_result(self, msg):
pass
| 5 | 0 | 10 | 2 | 9 | 0 | 1 | 0 | 2 | 1 | 0 | 0 | 3 | 1 | 3 | 22 | 28 | 6 | 22 | 10 | 17 | 0 | 16 | 10 | 11 | 1 | 4 | 0 | 4 |
4,451 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/loop.py
|
amanobot.aio.loop.MessageLoop
|
class MessageLoop():
def __init__(self, bot, handle=None):
self._bot = bot
self._handle = _infer_handler_function(bot, handle)
self._task = None
async def run_forever(self, *args, **kwargs):
updatesloop = GetUpdatesLoop(self._bot,
lambda update:
self._handle(_extract_message(update)[1]))
self._task = self._bot.loop.create_task(updatesloop.run_forever(*args, **kwargs))
self._bot.scheduler.on_event(self._handle)
def cancel(self):
self._task.cancel()
|
class MessageLoop():
def __init__(self, bot, handle=None):
pass
async def run_forever(self, *args, **kwargs):
pass
def cancel(self):
pass
| 4 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 3 | 3 | 3 | 3 | 17 | 4 | 13 | 8 | 9 | 0 | 11 | 8 | 7 | 1 | 0 | 0 | 3 |
4,452 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/inline/inlinea.py
|
inlinea.InlineHandler
|
class InlineHandler(InlineUserHandler, AnswererMixin):
def on_inline_query(self, msg):
def compute_answer():
query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query')
print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)
articles = [{'type': 'article',
'id': 'abc', 'title': query_string, 'message_text': query_string}]
return articles
self.answerer.answer(msg, compute_answer)
def on_chosen_inline_result(self, msg):
from pprint import pprint
pprint(msg)
result_id, from_id, query_string = amanobot.glance(msg, flavor='chosen_inline_result')
print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
|
class InlineHandler(InlineUserHandler, AnswererMixin):
def on_inline_query(self, msg):
pass
def compute_answer():
pass
def on_chosen_inline_result(self, msg):
pass
| 4 | 0 | 8 | 2 | 6 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 2 | 0 | 2 | 21 | 19 | 5 | 14 | 8 | 9 | 0 | 13 | 8 | 8 | 1 | 4 | 0 | 3 |
4,453 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/helper.py
|
amanobot.aio.helper.DefaultRouterMixin
|
class DefaultRouterMixin():
def __init__(self, *args, **kwargs):
self._router = Router(flavor, {'chat': _create_invoker(self, 'on_chat_message'),
'callback_query': _create_invoker(self, 'on_callback_query'),
'inline_query': _create_invoker(self, 'on_inline_query'),
'chosen_inline_result': _create_invoker(self, 'on_chosen_inline_result'),
'shipping_query': _create_invoker(self, 'on_shipping_query'),
'pre_checkout_query': _create_invoker(self, 'on_pre_checkout_query'),
'_idle': _create_invoker(self, 'on__idle')})
super(DefaultRouterMixin, self).__init__(*args, **kwargs)
@property
def router(self):
""" See :class:`.helper.Router` """
return self._router
async def on_message(self, msg):
"""
Called when a message is received.
By default, call :meth:`Router.route` to handle the message.
"""
await self._router.route(msg)
|
class DefaultRouterMixin():
def __init__(self, *args, **kwargs):
pass
@property
def router(self):
''' See :class:`.helper.Router` '''
pass
async def on_message(self, msg):
'''
Called when a message is received.
By default, call :meth:`Router.route` to handle the message.
'''
pass
| 5 | 2 | 6 | 0 | 4 | 2 | 1 | 0.33 | 0 | 2 | 1 | 5 | 3 | 1 | 3 | 3 | 23 | 3 | 15 | 6 | 10 | 5 | 8 | 5 | 4 | 1 | 0 | 0 | 3 |
4,454 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/payment/payment.py
|
payment.OrderProcessor
|
class OrderProcessor(amanobot.helper.InvoiceHandler):
@staticmethod
def on_shipping_query(msg):
query_id, from_id, invoice_payload = amanobot.glance(msg, flavor='shipping_query')
print('Shipping query:')
pprint(msg)
bot.answerShippingQuery(
query_id, True,
shipping_options=[
ShippingOption(id='fedex', title='FedEx', prices=[
LabeledPrice(label='Local', amount=345),
LabeledPrice(label='International', amount=2345)]),
ShippingOption(id='dhl', title='DHL', prices=[
LabeledPrice(label='Local', amount=342),
LabeledPrice(label='International', amount=1234)])])
@staticmethod
def on_pre_checkout_query(msg):
query_id, from_id, invoice_payload = amanobot.glance(msg, flavor='pre_checkout_query')
print('Pre-Checkout query:')
pprint(msg)
bot.answerPreCheckoutQuery(query_id, True)
@staticmethod
def on_chat_message(msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if content_type == 'successful_payment':
print('Successful payment RECEIVED!!!')
pprint(msg)
else:
print('Chat message:')
pprint(msg)
|
class OrderProcessor(amanobot.helper.InvoiceHandler):
@staticmethod
def on_shipping_query(msg):
pass
@staticmethod
def on_pre_checkout_query(msg):
pass
@staticmethod
def on_chat_message(msg):
pass
| 7 | 0 | 10 | 2 | 9 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 18 | 38 | 8 | 30 | 10 | 23 | 0 | 18 | 7 | 14 | 2 | 3 | 1 | 4 |
4,455 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/helper.py
|
amanobot.aio.helper.Microphone
|
class Microphone():
def __init__(self):
self._queues = set()
def add(self, q):
self._queues.add(q)
def remove(self, q):
self._queues.remove(q)
def send(self, msg):
for q in self._queues:
try:
q.put_nowait(msg)
except asyncio.QueueFull:
traceback.print_exc()
pass
|
class Microphone():
def __init__(self):
pass
def add(self, q):
pass
def remove(self, q):
pass
def send(self, msg):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 0 | 1 | 0 | 0 | 4 | 1 | 4 | 4 | 17 | 3 | 14 | 7 | 9 | 0 | 14 | 7 | 9 | 3 | 0 | 2 | 6 |
4,456 |
AmanoTeam/amanobot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmanoTeam_amanobot/amanobot/namedtuple.py
|
amanobot.namedtuple._create_class.sub
|
class sub(base):
def __new__(cls, **kwargs):
# Map keys.
for oldkey, newkey in keymap:
if oldkey in kwargs:
kwargs[newkey] = kwargs[oldkey]
del kwargs[oldkey]
# Any unexpected arguments?
unexpected = set(kwargs.keys()) - set(super(sub, cls)._fields)
# Remove unexpected arguments and issue warning.
if unexpected:
for k in unexpected:
del kwargs[k]
s = ('Unexpected fields: ' + ', '.join(unexpected) + ''
'\nBot API seems to have added new fields to the returned data.'
' This version of namedtuple is not able to capture them.'
'\n\nPlease upgrade amanobot by:'
'\n sudo pip install amanobot --upgrade'
'\n\nIf you still see this message after upgrade, that means I am still working to bring the code'
' up-to-date. Please try upgrade again a few days later. In the meantime,'
' you can access the new fields the old-fashioned way, through the raw dictionary.')
warnings.warn(s, UserWarning)
# Convert non-simple values to namedtuples.
for key, func in conversions:
if key in kwargs:
if type(kwargs[key]) is dict:
kwargs[key] = func(**kwargs[key])
elif type(kwargs[key]) is list:
kwargs[key] = func(kwargs[key])
else:
raise RuntimeError('Can only convert dict or list')
return super(sub, cls).__new__(cls, **kwargs)
|
class sub(base):
def __new__(cls, **kwargs):
pass
| 2 | 0 | 37 | 6 | 27 | 4 | 9 | 0.14 | 1 | 7 | 0 | 0 | 1 | 0 | 1 | 1 | 38 | 6 | 28 | 7 | 26 | 4 | 19 | 7 | 17 | 9 | 1 | 3 | 9 |
4,457 |
AmanoTeam/amanobot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.CallbackQueryCoordinator.augment_bot.BotProxy
|
class BotProxy():
pass
|
class BotProxy():
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
4,458 |
AmanoTeam/amanobot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Answerer.answer.Worker
|
class Worker(threading.Thread):
def __init__(innerself):
super(Worker, innerself).__init__()
innerself._cancelled = False
def cancel(innerself):
innerself._cancelled = True
def run(innerself):
try:
query_id = inline_query['id']
if innerself._cancelled:
return
# Important: compute function must be thread-safe.
ans = compute_fn(*compute_args, **compute_kwargs)
if innerself._cancelled:
return
if isinstance(ans, list):
outerself._bot.answerInlineQuery(query_id, ans)
elif isinstance(ans, tuple):
outerself._bot.answerInlineQuery(query_id, *ans)
elif isinstance(ans, dict):
outerself._bot.answerInlineQuery(query_id, **ans)
else:
raise ValueError('Invalid answer format')
finally:
with outerself._lock:
# Delete only if I have NOT been cancelled.
if not innerself._cancelled:
del outerself._workers[from_id]
|
class Worker(threading.Thread):
def __init__(innerself):
pass
def cancel(innerself):
pass
def run(innerself):
pass
| 4 | 0 | 10 | 1 | 8 | 1 | 3 | 0.08 | 1 | 6 | 1 | 0 | 3 | 0 | 3 | 28 | 34 | 6 | 26 | 6 | 22 | 2 | 22 | 6 | 18 | 7 | 1 | 3 | 9 |
4,459 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatboxa_nodb.py
|
chatboxa_nodb.ChatBox
|
class ChatBox(amanobot.aio.DelegatorBot):
def __init__(self, token, owner_id):
self._owner_id = owner_id
self._seen = set()
self._store = UnreadStore()
super(ChatBox, self).__init__(token, [
# Here is a delegate to specially handle owner commands.
pave_event_space()(
per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20),
# Only one MessageSaver is ever spawned for entire application.
(per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])),
# For senders never seen before, send him a welcome message.
(self._is_newcomer, call(self._send_welcome)),
])
# seed-calculating function: use returned value to indicate whether to spawn a delegate
def _is_newcomer(self, msg):
if amanobot.is_event(msg):
return None
chat_id = msg['chat']['id']
if chat_id == self._owner_id: # Sender is owner
return None # No delegate spawned
if chat_id in self._seen: # Sender has been seen before
return None # No delegate spawned
self._seen.add(chat_id)
return [] # non-hashable ==> delegates are independent, no seed association is made.
async def _send_welcome(self, seed_tuple):
chat_id = seed_tuple[1]['chat']['id']
print('Sending welcome ...')
await self.sendMessage(chat_id, 'Hello!')
|
class ChatBox(amanobot.aio.DelegatorBot):
def __init__(self, token, owner_id):
pass
def _is_newcomer(self, msg):
pass
async def _send_welcome(self, seed_tuple):
pass
| 4 | 0 | 11 | 2 | 8 | 3 | 2 | 0.36 | 1 | 5 | 3 | 0 | 3 | 3 | 3 | 95 | 38 | 9 | 25 | 9 | 21 | 9 | 20 | 9 | 16 | 4 | 4 | 1 | 6 |
4,460 |
AmanoTeam/amanobot
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmanoTeam_amanobot/amanobot/aio/__init__.py
|
amanobot.aio.Bot.Scheduler
|
class Scheduler(object):
def __init__(self, loop):
self._loop = loop
self._callback = None
def on_event(self, callback):
self._callback = callback
def event_at(self, when, data):
delay = when - time.time()
return self._loop.call_later(delay, self._callback, data)
# call_at() uses event loop time, not unix time.
# May as well use call_later here.
def event_later(self, delay, data):
return self._loop.call_later(delay, self._callback, data)
def event_now(self, data):
return self._loop.call_soon(self._callback, data)
@staticmethod
def cancel(event):
return event.cancel()
|
class Scheduler(object):
def __init__(self, loop):
pass
def on_event(self, callback):
pass
def event_at(self, when, data):
pass
def event_later(self, delay, data):
pass
def event_now(self, data):
pass
@staticmethod
def cancel(event):
pass
| 8 | 0 | 2 | 0 | 2 | 0 | 1 | 0.13 | 1 | 0 | 0 | 0 | 5 | 2 | 6 | 6 | 23 | 5 | 16 | 11 | 8 | 2 | 15 | 10 | 8 | 1 | 1 | 0 | 6 |
4,461 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/callback/lover.py
|
lover.Lover
|
class Lover(amanobot.helper.ChatHandler):
keyboard = InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text='Yes', callback_data='yes'),
InlineKeyboardButton(text='um ...', callback_data='no'),
]])
def __init__(self, *args, **kwargs):
super(Lover, self).__init__(*args, **kwargs)
# Retrieve from database
global propose_records
if self.id in propose_records:
self._count, self._edit_msg_ident = propose_records[self.id]
self._editor = amanobot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None
else:
self._count = 0
self._edit_msg_ident = None
self._editor = None
def _propose(self):
self._count += 1
sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self.keyboard)
self._editor = amanobot.helper.Editor(self.bot, sent)
self._edit_msg_ident = amanobot.message_identifier(sent)
def _cancel_last(self):
if self._editor:
self._editor.editMessageReplyMarkup(reply_markup=None)
self._editor = None
self._edit_msg_ident = None
def on_chat_message(self, msg):
self._propose()
def on_callback_query(self, msg):
query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')
if query_data == 'yes':
self._cancel_last()
self.sender.sendMessage('Thank you!')
self.close()
else:
self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
self._cancel_last()
self._propose()
def on__idle(self, event):
self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
self.close()
def on_close(self, ex):
# Save to database
global propose_records
propose_records[self.id] = (self._count, self._edit_msg_ident)
|
class Lover(amanobot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
pass
def _propose(self):
pass
def _cancel_last(self):
pass
def on_chat_message(self, msg):
pass
def on_callback_query(self, msg):
pass
def on__idle(self, event):
pass
def on_close(self, ex):
pass
| 8 | 0 | 6 | 0 | 5 | 0 | 2 | 0.05 | 1 | 2 | 1 | 0 | 7 | 4 | 7 | 24 | 54 | 9 | 43 | 16 | 33 | 2 | 38 | 15 | 28 | 3 | 3 | 1 | 11 |
4,462 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Administrator
|
class Administrator():
"""
When you are dealing with a particular chat, it is tedious to have to supply
the same ``chat_id`` every time to get a chat's info or to perform administrative
tasks.
This object is a proxy to a bot's chat administration methods,
automatically fills in a fixed chat id for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``chat_id``:
- :meth:`.Bot.kickChatMember`
- :meth:`.Bot.unbanChatMember`
- :meth:`.Bot.restrictChatMember`
- :meth:`.Bot.promoteChatMember`
- :meth:`.Bot.exportChatInviteLink`
- :meth:`.Bot.setChatPhoto`
- :meth:`.Bot.deleteChatPhoto`
- :meth:`.Bot.setChatTitle`
- :meth:`.Bot.setChatDescription`
- :meth:`.Bot.pinChatMessage`
- :meth:`.Bot.unpinChatMessage`
- :meth:`.Bot.leaveChat`
- :meth:`.Bot.getChat`
- :meth:`.Bot.getChatAdministrators`
- :meth:`.Bot.getChatMembersCount`
- :meth:`.Bot.getChatMember`
- :meth:`.Bot.setChatStickerSet`
- :meth:`.Bot.deleteChatStickerSet`
"""
def __init__(self, bot, chat_id):
for method in ['kickChatMember',
'unbanChatMember',
'restrictChatMember',
'promoteChatMember',
'exportChatInviteLink',
'setChatPhoto',
'deleteChatPhoto',
'setChatTitle',
'setChatDescription',
'pinChatMessage',
'unpinChatMessage',
'leaveChat',
'getChat',
'getChatAdministrators',
'getChatMembersCount',
'getChatMember',
'setChatStickerSet',
'deleteChatStickerSet']:
setattr(self, method, partial(getattr(bot, method), chat_id))
|
class Administrator():
'''
When you are dealing with a particular chat, it is tedious to have to supply
the same ``chat_id`` every time to get a chat's info or to perform administrative
tasks.
This object is a proxy to a bot's chat administration methods,
automatically fills in a fixed chat id for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``chat_id``:
- :meth:`.Bot.kickChatMember`
- :meth:`.Bot.unbanChatMember`
- :meth:`.Bot.restrictChatMember`
- :meth:`.Bot.promoteChatMember`
- :meth:`.Bot.exportChatInviteLink`
- :meth:`.Bot.setChatPhoto`
- :meth:`.Bot.deleteChatPhoto`
- :meth:`.Bot.setChatTitle`
- :meth:`.Bot.setChatDescription`
- :meth:`.Bot.pinChatMessage`
- :meth:`.Bot.unpinChatMessage`
- :meth:`.Bot.leaveChat`
- :meth:`.Bot.getChat`
- :meth:`.Bot.getChatAdministrators`
- :meth:`.Bot.getChatMembersCount`
- :meth:`.Bot.getChatMember`
- :meth:`.Bot.setChatStickerSet`
- :meth:`.Bot.deleteChatStickerSet`
'''
def __init__(self, bot, chat_id):
pass
| 2 | 1 | 20 | 0 | 20 | 0 | 2 | 1.29 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 51 | 3 | 21 | 3 | 19 | 27 | 4 | 3 | 2 | 2 | 0 | 1 | 2 |
4,463 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/helper.py
|
amanobot.aio.helper.Answerer
|
class Answerer():
"""
When processing inline queries, ensures **at most one active task** per user id.
"""
def __init__(self, bot, loop=None):
self._bot = bot
self._loop = loop if loop is not None else asyncio.get_event_loop()
self._working_tasks = {}
def answer(self, inline_query, compute_fn, *compute_args, **compute_kwargs):
"""
Create a task that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding task is already working for a user, that task is cancelled,
thus ensuring at most one active task per user id.
:param inline_query:
The inline query to be processed. The originating user is inferred from ``msg['from']['id']``.
:param compute_fn:
A function whose returned value is given to :meth:`.Bot.answerInlineQuery` to send.
May return:
- a *list* of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_
- a *tuple* whose first element is a list of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_,
followed by positional arguments to be supplied to :meth:`.Bot.answerInlineQuery`
- a *dictionary* representing keyword arguments to be supplied to :meth:`.Bot.answerInlineQuery`
:param \*compute_args: positional arguments to ``compute_fn``
:param \*\*compute_kwargs: keyword arguments to ``compute_fn``
"""
from_id = inline_query['from']['id']
async def compute_and_answer():
try:
query_id = inline_query['id']
ans = await _invoke(compute_fn, *compute_args, **compute_kwargs)
if isinstance(ans, list):
await self._bot.answerInlineQuery(query_id, ans)
elif isinstance(ans, tuple):
await self._bot.answerInlineQuery(query_id, *ans)
elif isinstance(ans, dict):
await self._bot.answerInlineQuery(query_id, **ans)
else:
raise ValueError('Invalid answer format')
except CancelledError:
# Cancelled. Record has been occupied by new task. Don't touch.
raise
except:
# Die accidentally. Remove myself from record.
del self._working_tasks[from_id]
raise
else:
# Die naturally. Remove myself from record.
del self._working_tasks[from_id]
if from_id in self._working_tasks:
self._working_tasks[from_id].cancel()
t = self._loop.create_task(compute_and_answer())
self._working_tasks[from_id] = t
|
class Answerer():
'''
When processing inline queries, ensures **at most one active task** per user id.
'''
def __init__(self, bot, loop=None):
pass
def answer(self, inline_query, compute_fn, *compute_args, **compute_kwargs):
'''
Create a task that calls ``compute fn`` (along with additional arguments
``*compute_args`` and ``**compute_kwargs``), then applies the returned value to
:meth:`.Bot.answerInlineQuery` to answer the inline query.
If a preceding task is already working for a user, that task is cancelled,
thus ensuring at most one active task per user id.
:param inline_query:
The inline query to be processed. The originating user is inferred from ``msg['from']['id']``.
:param compute_fn:
A function whose returned value is given to :meth:`.Bot.answerInlineQuery` to send.
May return:
- a *list* of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_
- a *tuple* whose first element is a list of `InlineQueryResult <https://core.telegram.org/bots/api#inlinequeryresult>`_,
followed by positional arguments to be supplied to :meth:`.Bot.answerInlineQuery`
- a *dictionary* representing keyword arguments to be supplied to :meth:`.Bot.answerInlineQuery`
:param \*compute_args: positional arguments to ``compute_fn``
:param \*\*compute_kwargs: keyword arguments to ``compute_fn``
'''
pass
async def compute_and_answer():
pass
| 4 | 2 | 28 | 4 | 16 | 8 | 3 | 0.8 | 0 | 5 | 0 | 0 | 2 | 3 | 2 | 2 | 66 | 12 | 30 | 11 | 26 | 24 | 27 | 11 | 23 | 6 | 0 | 2 | 10 |
4,464 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/loop.py
|
amanobot.aio.loop.Webhook
|
class Webhook():
def __init__(self, bot, handle=None):
self._bot = bot
self._handle = _infer_handler_function(bot, handle)
async def run_forever(self):
self._bot.scheduler.on_event(self._handle)
def feed(self, data):
update = _dictify(data)
self._handle(_extract_message(update)[1])
|
class Webhook():
def __init__(self, bot, handle=None):
pass
async def run_forever(self):
pass
def feed(self, data):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 11 | 2 | 9 | 7 | 5 | 0 | 9 | 7 | 5 | 1 | 0 | 0 | 3 |
4,465 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/exception.py
|
amanobot.exception.StopListening
|
class StopListening(AmanobotException):
pass
|
class StopListening(AmanobotException):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
4,466 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/helper.py
|
amanobot.aio.helper.Monitor
|
class Monitor(helper.ListenerContext, DefaultRouterMixin):
def __init__(self, seed_tuple, capture, **kwargs):
"""
A delegate that never times-out, probably doing some kind of background monitoring
in the application. Most naturally paired with :func:`amanobot.aio.delegate.per_application`.
:param capture: a list of patterns for ``listener`` to capture
"""
bot, initial_msg, seed = seed_tuple
super(Monitor, self).__init__(bot, seed, **kwargs)
for pattern in capture:
self.listener.capture(pattern)
|
class Monitor(helper.ListenerContext, DefaultRouterMixin):
def __init__(self, seed_tuple, capture, **kwargs):
'''
A delegate that never times-out, probably doing some kind of background monitoring
in the application. Most naturally paired with :func:`amanobot.aio.delegate.per_application`.
:param capture: a list of patterns for ``listener`` to capture
'''
pass
| 2 | 1 | 12 | 2 | 5 | 5 | 2 | 0.83 | 2 | 1 | 0 | 1 | 1 | 0 | 1 | 8 | 13 | 2 | 6 | 4 | 4 | 5 | 6 | 4 | 4 | 2 | 1 | 1 | 2 |
4,467 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/loop.py
|
amanobot.aio.loop.GetUpdatesLoop
|
class GetUpdatesLoop():
def __init__(self, bot, on_update):
self._bot = bot
self._update_handler = on_update
async def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None):
"""
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool
"""
while 1:
try:
result = await self._bot.getUpdates(offset=offset,
timeout=timeout,
allowed_updates=allowed_updates,
_raise_errors=True)
# Once passed, this parameter is no longer needed.
allowed_updates = None
# No sort. Trust server to give messages in correct order.
for update in result:
self._update_handler(update)
offset = update['update_id'] + 1
except CancelledError:
break
except exception.BadHTTPResponse as e:
traceback.print_exc()
# Servers probably down. Wait longer.
if e.status == 502:
await asyncio.sleep(30)
except:
traceback.print_exc()
await asyncio.sleep(relax)
else:
await asyncio.sleep(relax)
|
class GetUpdatesLoop():
def __init__(self, bot, on_update):
pass
async def run_forever(self, relax=0.1, offset=None, timeout=20, allowed_updates=None):
'''
Process new updates in infinity loop
:param relax: float
:param offset: int
:param timeout: int
:param allowed_updates: bool
'''
pass
| 3 | 1 | 20 | 3 | 13 | 5 | 4 | 0.38 | 0 | 2 | 1 | 0 | 2 | 2 | 2 | 2 | 42 | 6 | 26 | 8 | 23 | 10 | 23 | 7 | 20 | 7 | 0 | 3 | 8 |
4,468 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/examples/chat/chatbox_nodb.py
|
chatbox_nodb.MessageSaver
|
class MessageSaver(amanobot.helper.Monitor):
def __init__(self, seed_tuple, store, exclude):
# The `capture` criteria means to capture all messages.
super(MessageSaver, self).__init__(seed_tuple, capture=[[lambda msg: not amanobot.is_event(msg)]])
self._store = store
self._exclude = exclude
# Store every message, except those whose sender is in the exclude list, or non-text messages.
def on_chat_message(self, msg):
content_type, chat_type, chat_id = amanobot.glance(msg)
if chat_id in self._exclude:
print('Chat id %d is excluded.' % chat_id)
return
if content_type != 'text':
print('Content type %s is ignored.' % content_type)
return
print('Storing message: %s' % msg)
self._store.put(msg)
|
class MessageSaver(amanobot.helper.Monitor):
def __init__(self, seed_tuple, store, exclude):
pass
def on_chat_message(self, msg):
pass
| 3 | 0 | 9 | 2 | 7 | 1 | 2 | 0.13 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 10 | 21 | 4 | 15 | 6 | 12 | 2 | 15 | 6 | 12 | 3 | 2 | 1 | 4 |
4,469 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.AnswererMixin
|
class AnswererMixin():
"""
Install an :class:`.Answerer` to handle inline query.
"""
Answerer = Answerer # let subclass customize Answerer class
def __init__(self, *args, **kwargs):
self._answerer = self.Answerer(self.bot)
super(AnswererMixin, self).__init__(*args, **kwargs)
@property
def answerer(self):
return self._answerer
|
class AnswererMixin():
'''
Install an :class:`.Answerer` to handle inline query.
'''
def __init__(self, *args, **kwargs):
pass
@property
def answerer(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.5 | 0 | 1 | 0 | 4 | 2 | 1 | 2 | 2 | 13 | 2 | 8 | 6 | 4 | 4 | 7 | 5 | 4 | 1 | 0 | 0 | 2 |
4,470 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.CallbackQueryCoordinator
|
class CallbackQueryCoordinator():
def __init__(self, id, origin_set, enable_chat, enable_inline):
"""
:param origin_set:
Callback query whose origin belongs to this set will be captured
:param enable_chat:
- ``False``: Do not intercept *chat-originated* callback query
- ``True``: Do intercept
- Notifier function: Do intercept and call the notifier function
on adding or removing an origin
:param enable_inline:
Same meaning as ``enable_chat``, but apply to *inline-originated*
callback query
Notifier functions should have the signature ``notifier(origin, id, adding)``:
- On adding an origin, ``notifier(origin, my_id, True)`` will be called.
- On removing an origin, ``notifier(origin, my_id, False)`` will be called.
"""
self._id = id
self._origin_set = origin_set
def dissolve(enable):
if not enable:
return False, None
if enable is True:
return True, None
if callable(enable):
return True, enable
raise ValueError()
self._enable_chat, self._chat_notify = dissolve(enable_chat)
self._enable_inline, self._inline_notify = dissolve(enable_inline)
def configure(self, listener):
"""
Configure a :class:`.Listener` to capture callback query
"""
listener.capture([
lambda msg: flavor(msg) == 'callback_query',
{'message': self._chat_origin_included}
])
listener.capture([
lambda msg: flavor(msg) == 'callback_query',
{'inline_message_id': self._inline_origin_included}
])
def _chat_origin_included(self, msg):
try:
return (msg['chat']['id'], msg['message_id']) in self._origin_set
except KeyError:
return False
def _inline_origin_included(self, inline_message_id):
return (inline_message_id,) in self._origin_set
def _rectify(self, msg_identifier):
if isinstance(msg_identifier, tuple):
if len(msg_identifier) == 2:
return msg_identifier, self._chat_notify
if len(msg_identifier) == 1:
return msg_identifier, self._inline_notify
raise ValueError()
else:
return (msg_identifier,), self._inline_notify
def capture_origin(self, msg_identifier, notify=True):
msg_identifier, notifier = self._rectify(msg_identifier)
self._origin_set.add(msg_identifier)
notify and notifier and notifier(msg_identifier, self._id, True)
def uncapture_origin(self, msg_identifier, notify=True):
msg_identifier, notifier = self._rectify(msg_identifier)
self._origin_set.discard(msg_identifier)
notify and notifier and notifier(msg_identifier, self._id, False)
@staticmethod
def _contains_callback_data(message_kw):
def contains(obj, key):
if isinstance(obj, dict):
return key in obj
return hasattr(obj, key)
if contains(message_kw, 'reply_markup'):
reply_markup = filtering.pick(message_kw, 'reply_markup')
if contains(reply_markup, 'inline_keyboard'):
inline_keyboard = filtering.pick(reply_markup, 'inline_keyboard')
for array in inline_keyboard:
if any(filter(lambda button: contains(button, 'callback_data'), array)):
return True
return False
def augment_send(self, send_func):
"""
:param send_func:
a function that sends messages, such as :meth:`.Bot.send\*`
:return:
a function that wraps around ``send_func`` and examines whether the
sent message contains an inline keyboard with callback data. If so,
future callback query originating from the sent message will be captured.
"""
def augmented(*aa, **kw):
sent = send_func(*aa, **kw)
if self._enable_chat and self._contains_callback_data(kw):
self.capture_origin(message_identifier(sent))
return sent
return augmented
def augment_edit(self, edit_func):
"""
:param edit_func:
a function that edits messages, such as :meth:`.Bot.edit*`
:return:
a function that wraps around ``edit_func`` and examines whether the
edited message contains an inline keyboard with callback data. If so,
future callback query originating from the edited message will be captured.
If not, such capturing will be stopped.
"""
def augmented(msg_identifier, *aa, **kw):
edited = edit_func(msg_identifier, *aa, **kw)
if (edited is True and self._enable_inline) or (isinstance(edited, dict) and self._enable_chat):
if self._contains_callback_data(kw):
self.capture_origin(msg_identifier)
else:
self.uncapture_origin(msg_identifier)
return edited
return augmented
def augment_delete(self, delete_func):
"""
:param delete_func:
a function that deletes messages, such as :meth:`.Bot.deleteMessage`
:return:
a function that wraps around ``delete_func`` and stops capturing
callback query originating from that deleted message.
"""
def augmented(msg_identifier, *aa, **kw):
deleted = delete_func(msg_identifier, *aa, **kw)
if deleted is True:
self.uncapture_origin(msg_identifier)
return deleted
return augmented
def augment_on_message(self, handler):
"""
:param handler:
an ``on_message()`` handler function
:return:
a function that wraps around ``handler`` and examines whether the
incoming message is a chosen inline result with an ``inline_message_id``
field. If so, future callback query originating from this chosen
inline result will be captured.
"""
def augmented(msg):
if (self._enable_inline
and flavor(msg) == 'chosen_inline_result'
and 'inline_message_id' in msg):
inline_message_id = msg['inline_message_id']
self.capture_origin(inline_message_id)
return handler(msg)
return augmented
def augment_bot(self, bot):
"""
:return:
a proxy to ``bot`` with these modifications:
- all ``send*`` methods augmented by :meth:`augment_send`
- all ``edit*`` methods augmented by :meth:`augment_edit`
- ``deleteMessage()`` augmented by :meth:`augment_delete`
- all other public methods, including properties, copied unchanged
"""
# Because a plain object cannot be set attributes, we need a class.
class BotProxy():
pass
proxy = BotProxy()
send_methods = ['sendMessage',
'forwardMessage',
'sendPhoto',
'sendAudio',
'sendDocument',
'sendSticker',
'sendVideo',
'sendVoice',
'sendVideoNote',
'sendLocation',
'sendVenue',
'sendContact',
'sendGame',
'sendInvoice',
'sendChatAction',]
for method in send_methods:
setattr(proxy, method, self.augment_send(getattr(bot, method)))
edit_methods = ['editMessageText',
'editMessageCaption',
'editMessageReplyMarkup',]
for method in edit_methods:
setattr(proxy, method, self.augment_edit(getattr(bot, method)))
delete_methods = ['deleteMessage']
for method in delete_methods:
setattr(proxy, method, self.augment_delete(getattr(bot, method)))
def public_untouched(nv):
name, value = nv
return (not name.startswith('_')
and name not in send_methods + edit_methods + delete_methods)
for name, value in filter(public_untouched, inspect.getmembers(bot)):
setattr(proxy, name, value)
return proxy
|
class CallbackQueryCoordinator():
def __init__(self, id, origin_set, enable_chat, enable_inline):
'''
:param origin_set:
Callback query whose origin belongs to this set will be captured
:param enable_chat:
- ``False``: Do not intercept *chat-originated* callback query
- ``True``: Do intercept
- Notifier function: Do intercept and call the notifier function
on adding or removing an origin
:param enable_inline:
Same meaning as ``enable_chat``, but apply to *inline-originated*
callback query
Notifier functions should have the signature ``notifier(origin, id, adding)``:
- On adding an origin, ``notifier(origin, my_id, True)`` will be called.
- On removing an origin, ``notifier(origin, my_id, False)`` will be called.
'''
pass
def dissolve(enable):
pass
def configure(self, listener):
'''
Configure a :class:`.Listener` to capture callback query
'''
pass
def _chat_origin_included(self, msg):
pass
def _inline_origin_included(self, inline_message_id):
pass
def _rectify(self, msg_identifier):
pass
def capture_origin(self, msg_identifier, notify=True):
pass
def uncapture_origin(self, msg_identifier, notify=True):
pass
@staticmethod
def _contains_callback_data(message_kw):
pass
def contains(obj, key):
pass
def augment_send(self, send_func):
'''
:param send_func:
a function that sends messages, such as :meth:`.Bot.send\*`
:return:
a function that wraps around ``send_func`` and examines whether the
sent message contains an inline keyboard with callback data. If so,
future callback query originating from the sent message will be captured.
'''
pass
def augmented(*aa, **kw):
pass
def augment_edit(self, edit_func):
'''
:param edit_func:
a function that edits messages, such as :meth:`.Bot.edit*`
:return:
a function that wraps around ``edit_func`` and examines whether the
edited message contains an inline keyboard with callback data. If so,
future callback query originating from the edited message will be captured.
If not, such capturing will be stopped.
'''
pass
def augmented(*aa, **kw):
pass
def augment_delete(self, delete_func):
'''
:param delete_func:
a function that deletes messages, such as :meth:`.Bot.deleteMessage`
:return:
a function that wraps around ``delete_func`` and stops capturing
callback query originating from that deleted message.
'''
pass
def augmented(*aa, **kw):
pass
def augment_on_message(self, handler):
'''
:param handler:
an ``on_message()`` handler function
:return:
a function that wraps around ``handler`` and examines whether the
incoming message is a chosen inline result with an ``inline_message_id``
field. If so, future callback query originating from this chosen
inline result will be captured.
'''
pass
def augmented(*aa, **kw):
pass
def augment_bot(self, bot):
'''
:return:
a proxy to ``bot`` with these modifications:
- all ``send*`` methods augmented by :meth:`augment_send`
- all ``edit*`` methods augmented by :meth:`augment_edit`
- ``deleteMessage()`` augmented by :meth:`augment_delete`
- all other public methods, including properties, copied unchanged
'''
pass
class BotProxy():
def public_untouched(nv):
pass
| 23 | 7 | 13 | 2 | 8 | 3 | 2 | 0.46 | 0 | 6 | 1 | 1 | 12 | 6 | 13 | 13 | 232 | 42 | 130 | 43 | 107 | 60 | 102 | 42 | 80 | 5 | 0 | 4 | 41 |
4,471 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.DefaultRouterMixin
|
class DefaultRouterMixin():
"""
Install a default :class:`.Router` and the instance method ``on_message()``.
"""
def __init__(self, *args, **kwargs):
self._router = Router(flavor, {'chat': lambda msg: self.on_chat_message(msg),
'callback_query': lambda msg: self.on_callback_query(msg),
'inline_query': lambda msg: self.on_inline_query(msg),
'chosen_inline_result': lambda msg: self.on_chosen_inline_result(msg),
'shipping_query': lambda msg: self.on_shipping_query(msg),
'pre_checkout_query': lambda msg: self.on_pre_checkout_query(msg),
'_idle': lambda event: self.on__idle(event)})
# use lambda to delay evaluation of self.on_ZZZ to runtime because
# I don't want to require defining all methods right here.
super(DefaultRouterMixin, self).__init__(*args, **kwargs)
@property
def router(self):
return self._router
def on_message(self, msg):
""" Call :meth:`.Router.route` to handle the message. """
self._router.route(msg)
|
class DefaultRouterMixin():
'''
Install a default :class:`.Router` and the instance method ``on_message()``.
'''
def __init__(self, *args, **kwargs):
pass
@property
def router(self):
pass
def on_message(self, msg):
''' Call :meth:`.Router.route` to handle the message. '''
pass
| 5 | 2 | 6 | 0 | 4 | 1 | 1 | 0.4 | 0 | 2 | 1 | 5 | 3 | 1 | 3 | 3 | 24 | 3 | 15 | 6 | 10 | 6 | 8 | 5 | 4 | 1 | 0 | 0 | 3 |
4,472 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.Editor
|
class Editor():
"""
If you want to edit a message over and over, it is tedious to have to supply
the same ``msg_identifier`` every time.
This object is a proxy to a bot's message-editing methods, automatically fills
in a fixed message identifier for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``msg_identifier``:
- :meth:`.Bot.editMessageText`
- :meth:`.Bot.editMessageCaption`
- :meth:`.Bot.editMessageReplyMarkup`
- :meth:`.Bot.deleteMessage`
- :meth:`.Bot.editMessageLiveLocation`
- :meth:`.Bot.stopMessageLiveLocation`
A message's identifier can be easily extracted with :func:`amanobot.message_identifier`.
"""
def __init__(self, bot, msg_identifier):
"""
:param msg_identifier:
a message identifier as mentioned above, or a message (whose
identifier will be automatically extracted).
"""
# Accept dict as argument. Maybe expand this convenience to other cases in future.
if isinstance(msg_identifier, dict):
msg_identifier = message_identifier(msg_identifier)
for method in ['editMessageText',
'editMessageCaption',
'editMessageReplyMarkup',
'deleteMessage',
'editMessageLiveLocation',
'stopMessageLiveLocation']:
setattr(self, method, partial(getattr(bot, method), msg_identifier))
|
class Editor():
'''
If you want to edit a message over and over, it is tedious to have to supply
the same ``msg_identifier`` every time.
This object is a proxy to a bot's message-editing methods, automatically fills
in a fixed message identifier for you. Available methods have
identical signatures as those of the underlying bot, **except there is no need
to supply the aforementioned** ``msg_identifier``:
- :meth:`.Bot.editMessageText`
- :meth:`.Bot.editMessageCaption`
- :meth:`.Bot.editMessageReplyMarkup`
- :meth:`.Bot.deleteMessage`
- :meth:`.Bot.editMessageLiveLocation`
- :meth:`.Bot.stopMessageLiveLocation`
A message's identifier can be easily extracted with :func:`amanobot.message_identifier`.
'''
def __init__(self, bot, msg_identifier):
'''
:param msg_identifier:
a message identifier as mentioned above, or a message (whose
identifier will be automatically extracted).
'''
pass
| 2 | 2 | 17 | 1 | 10 | 6 | 3 | 1.91 | 0 | 2 | 0 | 0 | 1 | 0 | 1 | 1 | 37 | 5 | 11 | 3 | 9 | 21 | 6 | 3 | 4 | 3 | 0 | 1 | 3 |
4,473 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/__init__.py
|
amanobot.aio.Bot
|
class Bot(_BotBase):
class Scheduler(object):
def __init__(self, loop):
self._loop = loop
self._callback = None
def on_event(self, callback):
self._callback = callback
def event_at(self, when, data):
delay = when - time.time()
return self._loop.call_later(delay, self._callback, data)
# call_at() uses event loop time, not unix time.
# May as well use call_later here.
def event_later(self, delay, data):
return self._loop.call_later(delay, self._callback, data)
def event_now(self, data):
return self._loop.call_soon(self._callback, data)
@staticmethod
def cancel(event):
return event.cancel()
def __init__(self, token: str, loop=None, raise_errors: bool = True, api_endpoint: str = "https://api.telegram.org"):
super(Bot, self).__init__(token, raise_errors, api_endpoint)
self._loop = loop or asyncio.get_event_loop()
api._loop = self._loop # sync loop with api module
self._scheduler = self.Scheduler(self._loop)
self._router = helper.Router(flavor, {'chat': helper._create_invoker(self, 'on_chat_message'),
'callback_query': helper._create_invoker(self, 'on_callback_query'),
'inline_query': helper._create_invoker(self, 'on_inline_query'),
'chosen_inline_result': helper._create_invoker(self, 'on_chosen_inline_result')})
@property
def loop(self):
return self._loop
@property
def scheduler(self):
return self._scheduler
@property
def router(self):
return self._router
async def handle(self, msg):
await self._router.route(msg)
async def _api_request(self, method, params=None, files=None, raise_errors=None, **kwargs):
return await api.request((self._base_url, self._token, method, params, files), **kwargs,
raise_errors=raise_errors if raise_errors is not None else self._raise_errors)
async def _api_request_with_file(self, method, params, files, **kwargs):
params.update({
k: v for k, v in files.items() if _isstring(v)})
files = {
k: v for k, v in files.items() if v is not None and not _isstring(v)}
return await self._api_request(method, _rectify(params), files, **kwargs)
async def getMe(self):
""" See: https://core.telegram.org/bots/api#getme """
return await self._api_request('getMe')
async def logOut(self):
""" See: https://core.telegram.org/bots/api#logout """
return await self._api_request('logOut')
async def close(self):
""" See: https://core.telegram.org/bots/api#close """
return await self._api_request('close')
async def sendMessage(self, chat_id: Union[int, str], text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendmessage """
p = _strip(locals())
return await self._api_request('sendMessage', _rectify(p))
async def forwardMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
""" See: https://core.telegram.org/bots/api#forwardmessage """
p = _strip(locals())
return await self._api_request('forwardMessage', _rectify(p))
async def copyMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#copymessage """
p = _strip(locals())
return await self._api_request('copyMessage', _rectify(p))
async def sendPhoto(self, chat_id: Union[int, str], photo,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendphoto
:param photo:
- string: ``file_id`` for a photo existing on Telegram servers
- string: HTTP URL of a photo from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (filename, file-like object).
"""
p = _strip(locals(), more=['photo'])
return await self._api_request_with_file('sendPhoto', _rectify(p), {'photo': photo})
async def sendAudio(self, chat_id: Union[int, str], audio,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
performer=None,
title=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendaudio
:param audio: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['audio', 'thumb'])
return await self._api_request_with_file('sendAudio', _rectify(p), {'audio': audio, 'thumb': thumb})
async def sendDocument(self, chat_id: Union[int, str], document,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_content_type_detection=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#senddocument
:param document: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['document', 'thumb'])
return await self._api_request_with_file('sendDocument', _rectify(p), {'document': document, 'thumb': thumb})
async def sendVideo(self, chat_id: Union[int, str], video,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
supports_streaming=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvideo
:param video: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['video', 'thumb'])
return await self._api_request_with_file('sendVideo', _rectify(p), {'video': video, 'thumb': thumb})
async def sendAnimation(self, chat_id: Union[int, str], animation,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendanimation
:param animation: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['animation', 'thumb'])
return await self._api_request_with_file('sendAnimation', _rectify(p), {'animation': animation, 'thumb': thumb})
async def sendVoice(self, chat_id: Union[int, str], voice,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvoice
:param voice: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['voice'])
return await self._api_request_with_file('sendVoice', _rectify(p), {'voice': voice})
async def sendVideoNote(self, chat_id: Union[int, str], video_note,
duration=None,
length=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendvideonote
:param video_note: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
:param length:
Although marked as optional, this method does not seem to work without
it being specified. Supply any integer you want. It seems to have no effect
on the video note's display size.
"""
p = _strip(locals(), more=['video_note', 'thumb'])
return await self._api_request_with_file('sendVideoNote', _rectify(p), {'video_note': video_note, 'thumb': thumb})
async def sendMediaGroup(self, chat_id: Union[int, str], media,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None):
"""
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
:param media:
To indicate media locations, each InputMedia object's ``media`` field
should be one of these:
- string: ``file_id`` for a file existing on Telegram servers
- string: HTTP URL of a file from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (form-data name, file-like object)
- tuple: (form-data name, (filename, file-like object))
In case of uploading, you may supply customized multipart/form-data
names for each uploaded file (as in last 2 options above). Otherwise,
amanobot assigns unique names to each uploaded file. Names assigned by
amanobot will not collide with user-supplied names, if any.
"""
p = _strip(locals(), more=['media'])
legal_media, files_to_attach = _split_input_media_array(media)
p['media'] = legal_media
return await self._api_request('sendMediaGroup', _rectify(p), files_to_attach)
async def sendLocation(self, chat_id: Union[int, str], latitude, longitude,
horizontal_accuracy=None,
live_period=None,
heading=None,
proximity_alert_radius=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendlocation """
p = _strip(locals())
return await self._api_request('sendLocation', _rectify(p))
async def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
horizontal_accuracy=None,
heading=None,
proximity_alert_radius=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('editMessageLiveLocation', _rectify(p))
async def stopMessageLiveLocation(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stopmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('stopMessageLiveLocation', _rectify(p))
async def sendVenue(self, chat_id: Union[int, str], latitude, longitude, title, address,
foursquare_id=None,
foursquare_type=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendvenue """
p = _strip(locals())
return await self._api_request('sendVenue', _rectify(p))
async def sendContact(self, chat_id: Union[int, str], phone_number, first_name,
last_name=None,
vcard=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendcontact """
p = _strip(locals())
return await self._api_request('sendContact', _rectify(p))
async def sendPoll(self, chat_id: Union[int, str], question, options,
is_anonymous=None,
type=None,
allows_multiple_answers=None,
correct_option_id=None,
explanation=None,
explanation_parse_mode: str = None,
open_period=None,
is_closed=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendpoll """
p = _strip(locals())
return await self._api_request('sendPoll', _rectify(p))
async def sendDice(self, chat_id: Union[int, str],
emoji=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#senddice """
p = _strip(locals())
return await self._api_request('sendDice', _rectify(p))
async def sendGame(self, chat_id: Union[int, str], game_short_name,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendgame """
p = _strip(locals())
return await self._api_request('sendGame', _rectify(p))
async def sendInvoice(self, chat_id: Union[int, str], title, description, payload,
provider_token, start_parameter, currency, prices,
provider_data=None,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,
need_name=None,
need_phone_number=None,
need_email=None,
need_shipping_address=None,
is_flexible=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
""" See: https://core.telegram.org/bots/api#sendinvoice """
p = _strip(locals())
return await self._api_request('sendInvoice', _rectify(p))
async def sendChatAction(self, chat_id: Union[int, str], action):
""" See: https://core.telegram.org/bots/api#sendchataction """
p = _strip(locals())
return await self._api_request('sendChatAction', _rectify(p))
async def getUserProfilePhotos(self, user_id,
offset=None,
limit=None):
""" See: https://core.telegram.org/bots/api#getuserprofilephotos """
p = _strip(locals())
return await self._api_request('getUserProfilePhotos', _rectify(p))
async def getFile(self, file_id):
""" See: https://core.telegram.org/bots/api#getfile """
p = _strip(locals())
return await self._api_request('getFile', _rectify(p))
async def kickChatMember(self, chat_id: Union[int, str], user_id,
until_date: int = None,
revoke_messages: bool = None):
""" See: https://core.telegram.org/bots/api#kickchatmember """
p = _strip(locals())
return await self._api_request('kickChatMember', _rectify(p))
async def unbanChatMember(self, chat_id: Union[int, str], user_id,
only_if_banned=None):
""" See: https://core.telegram.org/bots/api#unbanchatmember """
p = _strip(locals())
return await self._api_request('unbanChatMember', _rectify(p))
async def restrictChatMember(self, chat_id: Union[int, str], user_id,
until_date=None,
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
""" See: https://core.telegram.org/bots/api#restrictchatmember """
if not isinstance(permissions, dict):
permissions = dict(can_send_messages=can_send_messages,
can_send_media_messages=can_send_media_messages,
can_send_polls=can_send_polls,
can_send_other_messages=can_send_other_messages,
can_add_web_page_previews=can_add_web_page_previews,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages)
p = _strip(locals())
return await self._api_request('restrictChatMember', _rectify(p))
async def promoteChatMember(self, chat_id: Union[int, str], user_id,
is_anonymous=None,
can_manage_chat=None,
can_post_messages=None,
can_edit_messages=None,
can_delete_messages=None,
can_manage_voice_chats=None,
can_restrict_members=None,
can_promote_members=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None):
""" See: https://core.telegram.org/bots/api#promotechatmember """
p = _strip(locals())
return await self._api_request('promoteChatMember', _rectify(p))
async def setChatAdministratorCustomTitle(self, chat_id: Union[int, str], user_id,
custom_title):
""" See: https://core.telegram.org/bots/api#setchatadministratorcustomtitle """
p = _strip(locals())
return await self._api_request('setChatAdministratorCustomTitle', _rectify(p))
async def setChatPermissions(self, chat_id: Union[int, str],
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
""" See: https://core.telegram.org/bots/api#setchatpermissions """
if not isinstance(permissions, dict):
permissions = dict(can_send_messages=can_send_messages,
can_send_media_messages=can_send_media_messages,
can_send_polls=can_send_polls,
can_send_other_messages=can_send_other_messages,
can_add_web_page_previews=can_add_web_page_previews,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages)
p = _strip(locals())
return await self._api_request('setChatPermissions', _rectify(p))
async def exportChatInviteLink(self, chat_id):
""" See: https://core.telegram.org/bots/api#exportchatinvitelink """
p = _strip(locals())
return await self._api_request('exportChatInviteLink', _rectify(p))
async def createChatInviteLink(self, chat_id,
expire_date: int = None,
member_limit: int = None):
""" See: https://core.telegram.org/bots/api#createchatinvitelink """
p = _strip(locals())
return await self._api_request('createChatInviteLink', _rectify(p))
async def editChatInviteLink(self, chat_id,
invite_link: str,
expire_date: int = None,
member_limit: int = None):
""" See: https://core.telegram.org/bots/api#editchatinvitelink """
p = _strip(locals())
return await self._api_request('editChatInviteLink', _rectify(p))
async def revokeChatInviteLink(self, chat_id, invite_link: str):
""" See: https://core.telegram.org/bots/api#revokechatinvitelink """
p = _strip(locals())
return await self._api_request('revokeChatInviteLink', _rectify(p))
async def setChatPhoto(self, chat_id: Union[int, str], photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return await self._api_request_with_file('setChatPhoto', _rectify(p), {'photo': photo})
async def deleteChatPhoto(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatphoto """
p = _strip(locals())
return await self._api_request('deleteChatPhoto', _rectify(p))
async def setChatTitle(self, chat_id: Union[int, str], title):
""" See: https://core.telegram.org/bots/api#setchattitle """
p = _strip(locals())
return await self._api_request('setChatTitle', _rectify(p))
async def setChatDescription(self, chat_id: Union[int, str],
description=None):
""" See: https://core.telegram.org/bots/api#setchatdescription """
p = _strip(locals())
return await self._api_request('setChatDescription', _rectify(p))
async def pinChatMessage(self, chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
""" See: https://core.telegram.org/bots/api#pinchatmessage """
p = _strip(locals())
return await self._api_request('pinChatMessage', _rectify(p))
async def unpinChatMessage(self, chat_id: Union[int, str],
message_id=None):
""" See: https://core.telegram.org/bots/api#unpinchatmessage """
p = _strip(locals())
return await self._api_request('unpinChatMessage', _rectify(p))
async def unpinAllChatMessages(self, chat_id):
""" See: https://core.telegram.org/bots/api#unpinallchatmessages """
p = _strip(locals())
return await self._api_request('unpinAllChatMessages', _rectify(p))
async def leaveChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#leavechat """
p = _strip(locals())
return await self._api_request('leaveChat', _rectify(p))
async def getChat(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchat """
p = _strip(locals())
return await self._api_request('getChat', _rectify(p))
async def getChatAdministrators(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatadministrators """
p = _strip(locals())
return await self._api_request('getChatAdministrators', _rectify(p))
async def getChatMembersCount(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatmemberscount """
p = _strip(locals())
return await self._api_request('getChatMembersCount', _rectify(p))
async def getChatMember(self, chat_id: Union[int, str], user_id):
""" See: https://core.telegram.org/bots/api#getchatmember """
p = _strip(locals())
return await self._api_request('getChatMember', _rectify(p))
async def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
""" See: https://core.telegram.org/bots/api#setchatstickerset """
p = _strip(locals())
return await self._api_request('setChatStickerSet', _rectify(p))
async def deleteChatStickerSet(self, chat_id):
""" See: https://core.telegram.org/bots/api#deletechatstickerset """
p = _strip(locals())
return await self._api_request('deleteChatStickerSet', _rectify(p))
async def answerCallbackQuery(self, callback_query_id,
text=None,
show_alert=None,
url=None,
cache_time=None):
""" See: https://core.telegram.org/bots/api#answercallbackquery """
p = _strip(locals())
return await self._api_request('answerCallbackQuery', _rectify(p))
async def setMyCommands(self, commands=None):
""" See: https://core.telegram.org/bots/api#setmycommands """
if commands is None:
commands = []
p = _strip(locals())
return await self._api_request('setMyCommands', _rectify(p))
async def getMyCommands(self):
""" See: https://core.telegram.org/bots/api#getmycommands """
return await self._api_request('getMyCommands')
async def answerShippingQuery(self, shipping_query_id, ok,
shipping_options=None,
error_message=None):
""" See: https://core.telegram.org/bots/api#answershippingquery """
p = _strip(locals())
return await self._api_request('answerShippingQuery', _rectify(p))
async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
""" See: https://core.telegram.org/bots/api#answerprecheckoutquery """
p = _strip(locals())
return await self._api_request('answerPreCheckoutQuery', _rectify(p))
async def setPassportDataErrors(self, user_id, errors):
""" See: https://core.telegram.org/bots/api#setpassportdataerrors """
p = _strip(locals())
return await self._api_request('setPassportDataErrors', _rectify(p))
async def editMessageText(self, msg_identifier, text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`amanobot.message_identifier`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('editMessageText', _rectify(p))
async def editMessageCaption(self, msg_identifier,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('editMessageCaption', _rectify(p))
async def editMessageMedia(self, msg_identifier, media,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('editMessageMedia', _rectify(p))
async def editMessageReplyMarkup(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagereplymarkup
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('editMessageReplyMarkup', _rectify(p))
async def stopPoll(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``).
You may extract this value easily with :meth:`amanobot.message_identifier`
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('stopPoll', _rectify(p))
async def deleteMessage(self, msg_identifier):
"""
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`,
except this method does not work on inline messages.
"""
p = _strip(locals(), more=['msg_identifier'])
p.update(_dismantle_message_identifier(msg_identifier))
return await self._api_request('deleteMessage', _rectify(p))
async def sendSticker(self, chat_id: Union[int, str], sticker,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
"""
p = _strip(locals(), more=['sticker'])
return await self._api_request_with_file('sendSticker', _rectify(p), {'sticker': sticker})
async def getStickerSet(self, name):
"""
See: https://core.telegram.org/bots/api#getstickerset
"""
p = _strip(locals())
return await self._api_request('getStickerSet', _rectify(p))
async def uploadStickerFile(self, user_id, png_sticker):
"""
See: https://core.telegram.org/bots/api#uploadstickerfile
"""
p = _strip(locals(), more=['png_sticker'])
return await self._api_request_with_file('uploadStickerFile', _rectify(p), {'png_sticker': png_sticker})
async def createNewStickerSet(self, user_id, name, title, emojis,
png_sticker=None,
tgs_sticker=None,
contains_masks=None,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#createnewstickerset
"""
p = _strip(locals(), more=['png_sticker', 'tgs_sticker'])
return await self._api_request_with_file('createNewStickerSet', _rectify(p), {'png_sticker': png_sticker, 'tgs_sticker': tgs_sticker})
async def addStickerToSet(self, user_id, name, emojis,
png_sticker=None,
tgs_sticker=None,
mask_position=None):
"""
See: https://core.telegram.org/bots/api#addstickertoset
"""
p = _strip(locals(), more=['png_sticker', 'tgs_sticker'])
return await self._api_request_with_file('addStickerToSet', _rectify(p), {'png_sticker': png_sticker, 'tgs_sticker': tgs_sticker})
async def setStickerPositionInSet(self, sticker, position):
"""
See: https://core.telegram.org/bots/api#setstickerpositioninset
"""
p = _strip(locals())
return await self._api_request('setStickerPositionInSet', _rectify(p))
async def deleteStickerFromSet(self, sticker):
"""
See: https://core.telegram.org/bots/api#deletestickerfromset
"""
p = _strip(locals())
return await self._api_request('deleteStickerFromSet', _rectify(p))
async def setStickerSetThumb(self, name, user_id,
thumb=None):
"""
See: https://core.telegram.org/bots/api#setstickersetthumb
"""
p = _strip(locals(), more=['thumb'])
return await self._api_request_with_file('setStickerSetThumb', _rectify(p), {'thumb': thumb})
async def answerInlineQuery(self, inline_query_id, results,
cache_time=None,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None):
""" See: https://core.telegram.org/bots/api#answerinlinequery """
p = _strip(locals())
return await self._api_request('answerInlineQuery', _rectify(p))
async def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None,
_raise_errors=None):
""" See: https://core.telegram.org/bots/api#getupdates """
if _raise_errors is None:
_raise_errors = self._raise_errors
p = _strip(locals())
return await self._api_request('getUpdates', _rectify(p), raise_errors=_raise_errors)
async def setWebhook(self,
url=None,
certificate=None,
ip_address=None,
max_connections=None,
allowed_updates=None,
drop_pending_updates=None):
""" See: https://core.telegram.org/bots/api#setwebhook """
p = _strip(locals(), more=['certificate'])
if certificate:
files = {'certificate': certificate}
return await self._api_request('setWebhook', _rectify(p), files)
return await self._api_request('setWebhook', _rectify(p))
async def deleteWebhook(self,
drop_pending_updates=None):
p = _strip(locals())
""" See: https://core.telegram.org/bots/api#deletewebhook """
return await self._api_request('deleteWebhook', _rectify(p))
async def getWebhookInfo(self):
""" See: https://core.telegram.org/bots/api#getwebhookinfo """
return await self._api_request('getWebhookInfo')
async def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
""" See: https://core.telegram.org/bots/api#setgamescore """
p = _strip(locals(), more=['game_message_identifier'])
p.update(_dismantle_message_identifier(game_message_identifier))
return await self._api_request('setGameScore', _rectify(p))
async def getGameHighScores(self, user_id, game_message_identifier):
""" See: https://core.telegram.org/bots/api#getgamehighscores """
p = _strip(locals(), more=['game_message_identifier'])
p.update(_dismantle_message_identifier(game_message_identifier))
return await self._api_request('getGameHighScores', _rectify(p))
async def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = await self.getFile(file_id)
try:
d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb')
session, request = api.download((self._base_url, self._token, f['file_path']))
async with session:
async with request as r:
while 1:
chunk = await r.content.read(self._file_chunk_size)
if not chunk:
break
d.write(chunk)
d.flush()
finally:
if not isinstance(dest, io.IOBase) and 'd' in locals():
d.close()
async def message_loop(self, handler=None, relax=0.1,
timeout=20, allowed_updates=None,
source=None, ordered=True, maxhold=3):
"""
Return a task to constantly ``getUpdates`` or pull updates from a queue.
Apply ``handler`` to every message received.
:param handler:
a function that takes one argument (the message), or a routing table.
If ``None``, the bot's ``handle`` method is used.
A *routing table* is a dictionary of ``{flavor: function}``, mapping messages to appropriate
handler functions according to their flavors. It allows you to define functions specifically
to handle one flavor of messages. It usually looks like this: ``{'chat': fn1,
'callback_query': fn2, 'inline_query': fn3, ...}``. Each handler function should take
one argument (the message).
:param relax:
seconds between each ``getUpdates``
:type timeout: int
:param timeout:
``timeout`` parameter supplied to :meth:`amanobot.aio.Bot.getUpdates`,
controlling how long to poll in seconds.
:type allowed_updates: array of string
:param allowed_updates:
``allowed_updates`` parameter supplied to :meth:`amanobot.aio.Bot.getUpdates`,
controlling which types of updates to receive.
:param source:
Source of updates.
If ``None``, ``getUpdates`` is used to obtain new messages from Telegram servers.
If it is a ``asyncio.Queue``, new messages are pulled from the queue.
A web application implementing a webhook can dump updates into the queue,
while the bot pulls from it. This is how amanobot can be integrated with webhooks.
Acceptable contents in queue:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
When ``source`` is a queue, these parameters are meaningful:
:type ordered: bool
:param ordered:
If ``True``, ensure in-order delivery of messages to ``handler``
(i.e. updates with a smaller ``update_id`` always come before those with
a larger ``update_id``).
If ``False``, no re-ordering is done. ``handler`` is applied to messages
as soon as they are pulled from queue.
:type maxhold: float
:param maxhold:
Applied only when ``ordered`` is ``True``. The maximum number of seconds
an update is held waiting for a not-yet-arrived smaller ``update_id``.
When this number of seconds is up, the update is delivered to ``handler``
even if some smaller ``update_id``\s have not yet arrived. If those smaller
``update_id``\s arrive at some later time, they are discarded.
"""
if handler is None:
handler = self.handle
elif isinstance(handler, dict):
handler = flavor_router(handler)
def create_task_for(msg):
self.loop.create_task(handler(msg))
if asyncio.iscoroutinefunction(handler):
callback = create_task_for
else:
callback = handler
def handle(update):
try:
key = _find_first_key(update, ['message',
'edited_message',
'channel_post',
'edited_channel_post',
'inline_query',
'chosen_inline_result',
'callback_query',
'shipping_query',
'pre_checkout_query',
'poll',
'poll_answer',
'my_chat_member',
'chat_member'])
callback(update[key])
except:
# Localize the error so message thread can keep going.
traceback.print_exc()
finally:
return update['update_id']
async def get_from_telegram_server():
offset = None # running offset
allowed_upd = allowed_updates
while 1:
try:
result = await self.getUpdates(offset=offset,
timeout=timeout,
allowed_updates=allowed_upd,
_raise_errors=True)
# Once passed, this parameter is no longer needed.
allowed_upd = None
if len(result) > 0:
# No sort. Trust server to give messages in correct order.
# Update offset to max(update_id) + 1
offset = max([handle(update) for update in result]) + 1
except CancelledError:
raise
except exception.BadHTTPResponse as e:
traceback.print_exc()
# Servers probably down. Wait longer.
if e.status == 502:
await asyncio.sleep(30)
except:
traceback.print_exc()
await asyncio.sleep(relax)
else:
await asyncio.sleep(relax)
def dictify(data):
if type(data) is bytes:
return json.loads(data.decode('utf-8'))
if type(data) is str:
return json.loads(data)
if type(data) is dict:
return data
raise ValueError()
async def get_from_queue_unordered(qu):
while 1:
try:
data = await qu.get()
update = dictify(data)
handle(update)
except:
traceback.print_exc()
async def get_from_queue(qu):
# Here is the re-ordering mechanism, ensuring in-order delivery of updates.
max_id = None # max update_id passed to callback
buffer = collections.deque() # keep those updates which skip some update_id
qwait = None # how long to wait for updates,
# because buffer's content has to be returned in time.
while 1:
try:
data = await asyncio.wait_for(qu.get(), qwait)
update = dictify(data)
if max_id is None:
# First message received, handle regardless.
max_id = handle(update)
elif update['update_id'] == max_id + 1:
# No update_id skipped, handle naturally.
max_id = handle(update)
# clear contagious updates in buffer
if len(buffer) > 0:
buffer.popleft() # first element belongs to update just received, useless now.
while 1:
try:
if type(buffer[0]) is dict:
max_id = handle(buffer.popleft()) # updates that arrived earlier, handle them.
else:
break # gap, no more contagious updates
except IndexError:
break # buffer empty
elif update['update_id'] > max_id + 1:
# Update arrives pre-maturely, insert to buffer.
nbuf = len(buffer)
if update['update_id'] <= max_id + nbuf:
# buffer long enough, put update at position
buffer[update['update_id'] - max_id - 1] = update
else:
# buffer too short, lengthen it
expire = time.time() + maxhold
for a in range(nbuf, update['update_id']-max_id-1):
buffer.append(expire) # put expiry time in gaps
buffer.append(update)
else:
pass # discard
except asyncio.TimeoutError:
# debug message
# print('Timeout')
# some buffer contents have to be handled
# flush buffer until a non-expired time is encountered
while 1:
try:
if type(buffer[0]) is dict:
max_id = handle(buffer.popleft())
else:
expire = buffer[0]
if expire <= time.time():
max_id += 1
buffer.popleft()
else:
break # non-expired
except IndexError:
break # buffer empty
except:
traceback.print_exc()
finally:
try:
# don't wait longer than next expiry time
qwait = buffer[0] - time.time()
qwait = max(qwait, 0)
except IndexError:
# buffer empty, can wait forever
qwait = None
# debug message
# print ('Buffer:', str(buffer), ', To Wait:', qwait, ', Max ID:', max_id)
self._scheduler._callback = callback
if source is None:
await get_from_telegram_server()
elif isinstance(source, asyncio.Queue):
if ordered:
await get_from_queue(source)
else:
await get_from_queue_unordered(source)
else:
raise ValueError('Invalid source')
|
class Bot(_BotBase):
class Scheduler(object):
def __init__(self, loop):
pass
def on_event(self, callback):
pass
def event_at(self, when, data):
pass
def event_later(self, delay, data):
pass
def event_now(self, data):
pass
@staticmethod
def cancel(event):
pass
def __init__(self, loop):
pass
@property
def loop(self):
pass
@property
def scheduler(self):
pass
@property
def router(self):
pass
async def handle(self, msg):
pass
async def _api_request(self, method, params=None, files=None, raise_errors=None, **kwargs):
pass
async def _api_request_with_file(self, method, params, files, **kwargs):
pass
async def getMe(self):
''' See: https://core.telegram.org/bots/api#getme '''
pass
async def logOut(self):
''' See: https://core.telegram.org/bots/api#logout '''
pass
async def close(self):
''' See: https://core.telegram.org/bots/api#close '''
pass
async def sendMessage(self, chat_id: Union[int, str], text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendmessage '''
pass
async def forwardMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
''' See: https://core.telegram.org/bots/api#forwardmessage '''
pass
async def copyMessage(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#copymessage '''
pass
async def sendPhoto(self, chat_id: Union[int, str], photo,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendphoto
:param photo:
- string: ``file_id`` for a photo existing on Telegram servers
- string: HTTP URL of a photo from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (filename, file-like object).
'''
pass
async def sendAudio(self, chat_id: Union[int, str], audio,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
performer=None,
title=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendaudio
:param audio: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def sendDocument(self, chat_id: Union[int, str], document,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_content_type_detection=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#senddocument
:param document: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def sendVideo(self, chat_id: Union[int, str], video,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
supports_streaming=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvideo
:param video: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def sendAnimation(self, chat_id: Union[int, str], animation,
duration=None,
width=None,
height=None,
thumb=None,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendanimation
:param animation: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def sendVoice(self, chat_id: Union[int, str], voice,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
duration=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvoice
:param voice: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def sendVideoNote(self, chat_id: Union[int, str], video_note,
duration=None,
length=None,
thumb=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendvideonote
:param video_note: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
:param length:
Although marked as optional, this method does not seem to work without
it being specified. Supply any integer you want. It seems to have no effect
on the video note's display size.
'''
pass
async def sendMediaGroup(self, chat_id: Union[int, str], media,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None):
'''
See: https://core.telegram.org/bots/api#sendmediagroup
:type media: array of `InputMedia <https://core.telegram.org/bots/api#inputmedia>`_ objects
:param media:
To indicate media locations, each InputMedia object's ``media`` field
should be one of these:
- string: ``file_id`` for a file existing on Telegram servers
- string: HTTP URL of a file from the Internet
- file-like object: obtained by ``open(path, 'rb')``
- tuple: (form-data name, file-like object)
- tuple: (form-data name, (filename, file-like object))
In case of uploading, you may supply customized multipart/form-data
names for each uploaded file (as in last 2 options above). Otherwise,
amanobot assigns unique names to each uploaded file. Names assigned by
amanobot will not collide with user-supplied names, if any.
'''
pass
async def sendLocation(self, chat_id: Union[int, str], latitude, longitude,
horizontal_accuracy=None,
live_period=None,
heading=None,
proximity_alert_radius=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendlocation '''
pass
async def editMessageLiveLocation(self, msg_identifier, latitude, longitude,
horizontal_accuracy=None,
heading=None,
proximity_alert_radius=None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
'''
pass
async def stopMessageLiveLocation(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#stopmessagelivelocation
:param msg_identifier: Same as in :meth:`.Bot.editMessageText`
'''
pass
async def sendVenue(self, chat_id: Union[int, str], latitude, longitude, title, address,
foursquare_id=None,
foursquare_type=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendvenue '''
pass
async def sendContact(self, chat_id: Union[int, str], phone_number, first_name,
last_name=None,
vcard=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendcontact '''
pass
async def sendPoll(self, chat_id: Union[int, str], question, options,
is_anonymous=None,
type=None,
allows_multiple_answers=None,
correct_option_id=None,
explanation=None,
explanation_parse_mode: str = None,
open_period=None,
is_closed=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendpoll '''
pass
async def sendDice(self, chat_id: Union[int, str],
emoji=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#senddice '''
pass
async def sendGame(self, chat_id: Union[int, str], game_short_name,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendgame '''
pass
async def sendInvoice(self, chat_id: Union[int, str], title, description, payload,
provider_token, start_parameter, currency, prices,
provider_data=None,
photo_url=None,
photo_size=None,
photo_width=None,
photo_height=None,
need_name=None,
need_phone_number=None,
need_email=None,
need_shipping_address=None,
is_flexible=None,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
''' See: https://core.telegram.org/bots/api#sendinvoice '''
pass
async def sendChatAction(self, chat_id: Union[int, str], action):
''' See: https://core.telegram.org/bots/api#sendchataction '''
pass
async def getUserProfilePhotos(self, user_id,
offset=None,
limit=None):
''' See: https://core.telegram.org/bots/api#getuserprofilephotos '''
pass
async def getFile(self, file_id):
''' See: https://core.telegram.org/bots/api#getfile '''
pass
async def kickChatMember(self, chat_id: Union[int, str], user_id,
until_date: int = None,
revoke_messages: bool = None):
''' See: https://core.telegram.org/bots/api#kickchatmember '''
pass
async def unbanChatMember(self, chat_id: Union[int, str], user_id,
only_if_banned=None):
''' See: https://core.telegram.org/bots/api#unbanchatmember '''
pass
async def restrictChatMember(self, chat_id: Union[int, str], user_id,
until_date=None,
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
''' See: https://core.telegram.org/bots/api#restrictchatmember '''
pass
async def promoteChatMember(self, chat_id: Union[int, str], user_id,
is_anonymous=None,
can_manage_chat=None,
can_post_messages=None,
can_edit_messages=None,
can_delete_messages=None,
can_manage_voice_chats=None,
can_restrict_members=None,
can_promote_members=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None):
''' See: https://core.telegram.org/bots/api#promotechatmember '''
pass
async def setChatAdministratorCustomTitle(self, chat_id: Union[int, str], user_id,
custom_title):
''' See: https://core.telegram.org/bots/api#setchatadministratorcustomtitle '''
pass
async def setChatPermissions(self, chat_id: Union[int, str],
can_send_messages=None,
can_send_media_messages=None,
can_send_polls=None,
can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None,
can_invite_users=None,
can_pin_messages=None,
permissions=None):
''' See: https://core.telegram.org/bots/api#setchatpermissions '''
pass
async def exportChatInviteLink(self, chat_id):
''' See: https://core.telegram.org/bots/api#exportchatinvitelink '''
pass
async def createChatInviteLink(self, chat_id,
expire_date: int = None,
member_limit: int = None):
''' See: https://core.telegram.org/bots/api#createchatinvitelink '''
pass
async def editChatInviteLink(self, chat_id,
invite_link: str,
expire_date: int = None,
member_limit: int = None):
''' See: https://core.telegram.org/bots/api#editchatinvitelink '''
pass
async def revokeChatInviteLink(self, chat_id, invite_link: str):
''' See: https://core.telegram.org/bots/api#revokechatinvitelink '''
pass
async def setChatPhoto(self, chat_id: Union[int, str], photo):
''' See: https://core.telegram.org/bots/api#setchatphoto '''
pass
async def deleteChatPhoto(self, chat_id):
''' See: https://core.telegram.org/bots/api#deletechatphoto '''
pass
async def setChatTitle(self, chat_id: Union[int, str], title):
''' See: https://core.telegram.org/bots/api#setchattitle '''
pass
async def setChatDescription(self, chat_id: Union[int, str],
description=None):
''' See: https://core.telegram.org/bots/api#setchatdescription '''
pass
async def pinChatMessage(self, chat_id: Union[int, str], message_id: int,
disable_notification: bool = None):
''' See: https://core.telegram.org/bots/api#pinchatmessage '''
pass
async def unpinChatMessage(self, chat_id: Union[int, str],
message_id=None):
''' See: https://core.telegram.org/bots/api#unpinchatmessage '''
pass
async def unpinAllChatMessages(self, chat_id):
''' See: https://core.telegram.org/bots/api#unpinallchatmessages '''
pass
async def leaveChat(self, chat_id):
''' See: https://core.telegram.org/bots/api#leavechat '''
pass
async def getChat(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchat '''
pass
async def getChatAdministrators(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatadministrators '''
pass
async def getChatMembersCount(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatmemberscount '''
pass
async def getChatMembersCount(self, chat_id):
''' See: https://core.telegram.org/bots/api#getchatmember '''
pass
async def setChatStickerSet(self, chat_id: Union[int, str], sticker_set_name):
''' See: https://core.telegram.org/bots/api#setchatstickerset '''
pass
async def deleteChatStickerSet(self, chat_id):
''' See: https://core.telegram.org/bots/api#deletechatstickerset '''
pass
async def answerCallbackQuery(self, callback_query_id,
text=None,
show_alert=None,
url=None,
cache_time=None):
''' See: https://core.telegram.org/bots/api#answercallbackquery '''
pass
async def setMyCommands(self, commands=None):
''' See: https://core.telegram.org/bots/api#setmycommands '''
pass
async def getMyCommands(self):
''' See: https://core.telegram.org/bots/api#getmycommands '''
pass
async def answerShippingQuery(self, shipping_query_id, ok,
shipping_options=None,
error_message=None):
''' See: https://core.telegram.org/bots/api#answershippingquery '''
pass
async def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
''' See: https://core.telegram.org/bots/api#answerprecheckoutquery '''
pass
async def setPassportDataErrors(self, user_id, errors):
''' See: https://core.telegram.org/bots/api#setpassportdataerrors '''
pass
async def editMessageText(self, msg_identifier, text: str,
parse_mode: str = None,
entities=None,
disable_web_page_preview: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagetext
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`amanobot.message_identifier`
'''
pass
async def editMessageCaption(self, msg_identifier,
caption: str = None,
parse_mode: str = None,
caption_entities=None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
'''
pass
async def editMessageMedia(self, msg_identifier, media,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagemedia
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
'''
pass
async def editMessageReplyMarkup(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#editmessagereplymarkup
:param msg_identifier: Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`
'''
pass
async def stopPoll(self, msg_identifier,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``).
You may extract this value easily with :meth:`amanobot.message_identifier`
'''
pass
async def deleteMessage(self, msg_identifier):
'''
See: https://core.telegram.org/bots/api#deletemessage
:param msg_identifier:
Same as ``msg_identifier`` in :meth:`amanobot.aio.Bot.editMessageText`,
except this method does not work on inline messages.
'''
pass
async def sendSticker(self, chat_id: Union[int, str], sticker,
disable_notification: bool = None,
reply_to_message_id: int = None,
allow_sending_without_reply: bool = None,
reply_markup=None):
'''
See: https://core.telegram.org/bots/api#sendsticker
:param sticker: Same as ``photo`` in :meth:`amanobot.aio.Bot.sendPhoto`
'''
pass
async def getStickerSet(self, name):
'''
See: https://core.telegram.org/bots/api#getstickerset
'''
pass
async def uploadStickerFile(self, user_id, png_sticker):
'''
See: https://core.telegram.org/bots/api#uploadstickerfile
'''
pass
async def createNewStickerSet(self, user_id, name, title, emojis,
png_sticker=None,
tgs_sticker=None,
contains_masks=None,
mask_position=None):
'''
See: https://core.telegram.org/bots/api#createnewstickerset
'''
pass
async def addStickerToSet(self, user_id, name, emojis,
png_sticker=None,
tgs_sticker=None,
mask_position=None):
'''
See: https://core.telegram.org/bots/api#addstickertoset
'''
pass
async def setStickerPositionInSet(self, sticker, position):
'''
See: https://core.telegram.org/bots/api#setstickerpositioninset
'''
pass
async def deleteStickerFromSet(self, sticker):
'''
See: https://core.telegram.org/bots/api#deletestickerfromset
'''
pass
async def setStickerSetThumb(self, name, user_id,
thumb=None):
'''
See: https://core.telegram.org/bots/api#setstickersetthumb
'''
pass
async def answerInlineQuery(self, inline_query_id, results,
cache_time=None,
is_personal=None,
next_offset=None,
switch_pm_text=None,
switch_pm_parameter=None):
''' See: https://core.telegram.org/bots/api#answerinlinequery '''
pass
async def getUpdates(self,
offset=None,
limit=None,
timeout=None,
allowed_updates=None,
_raise_errors=None):
''' See: https://core.telegram.org/bots/api#getupdates '''
pass
async def setWebhook(self,
url=None,
certificate=None,
ip_address=None,
max_connections=None,
allowed_updates=None,
drop_pending_updates=None):
''' See: https://core.telegram.org/bots/api#setwebhook '''
pass
async def deleteWebhook(self,
drop_pending_updates=None):
pass
async def getWebhookInfo(self):
''' See: https://core.telegram.org/bots/api#getwebhookinfo '''
pass
async def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
''' See: https://core.telegram.org/bots/api#setgamescore '''
pass
async def getGameHighScores(self, user_id, game_message_identifier):
''' See: https://core.telegram.org/bots/api#getgamehighscores '''
pass
async def download_file(self, file_id, dest):
'''
Download a file to local disk.
:param dest: a path or a ``file`` object
'''
pass
async def message_loop(self, handler=None, relax=0.1,
timeout=20, allowed_updates=None,
source=None, ordered=True, maxhold=3):
'''
Return a task to constantly ``getUpdates`` or pull updates from a queue.
Apply ``handler`` to every message received.
:param handler:
a function that takes one argument (the message), or a routing table.
If ``None``, the bot's ``handle`` method is used.
A *routing table* is a dictionary of ``{flavor: function}``, mapping messages to appropriate
handler functions according to their flavors. It allows you to define functions specifically
to handle one flavor of messages. It usually looks like this: ``{'chat': fn1,
'callback_query': fn2, 'inline_query': fn3, ...}``. Each handler function should take
one argument (the message).
:param relax:
seconds between each ``getUpdates``
:type timeout: int
:param timeout:
``timeout`` parameter supplied to :meth:`amanobot.aio.Bot.getUpdates`,
controlling how long to poll in seconds.
:type allowed_updates: array of string
:param allowed_updates:
``allowed_updates`` parameter supplied to :meth:`amanobot.aio.Bot.getUpdates`,
controlling which types of updates to receive.
:param source:
Source of updates.
If ``None``, ``getUpdates`` is used to obtain new messages from Telegram servers.
If it is a ``asyncio.Queue``, new messages are pulled from the queue.
A web application implementing a webhook can dump updates into the queue,
while the bot pulls from it. This is how amanobot can be integrated with webhooks.
Acceptable contents in queue:
- ``str`` or ``bytes`` (decoded using UTF-8)
representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object.
- a ``dict`` representing an Update object.
When ``source`` is a queue, these parameters are meaningful:
:type ordered: bool
:param ordered:
If ``True``, ensure in-order delivery of messages to ``handler``
(i.e. updates with a smaller ``update_id`` always come before those with
a larger ``update_id``).
If ``False``, no re-ordering is done. ``handler`` is applied to messages
as soon as they are pulled from queue.
:type maxhold: float
:param maxhold:
Applied only when ``ordered`` is ``True``. The maximum number of seconds
an update is held waiting for a not-yet-arrived smaller ``update_id``.
When this number of seconds is up, the update is delivered to ``handler``
even if some smaller ``update_id``\s have not yet arrived. If those smaller
``update_id``\s arrive at some later time, they are discarded.
'''
pass
def create_task_for(msg):
pass
async def handle(self, msg):
pass
async def get_from_telegram_server():
pass
def dictify(data):
pass
async def get_from_queue_unordered(qu):
pass
async def get_from_queue_unordered(qu):
pass
| 104 | 78 | 12 | 1 | 8 | 3 | 1 | 0.37 | 1 | 16 | 3 | 2 | 86 | 5 | 86 | 87 | 1,099 | 156 | 699 | 445 | 356 | 257 | 406 | 199 | 306 | 18 | 1 | 7 | 143 |
4,474 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/aio/__init__.py
|
amanobot.aio.DelegatorBot
|
class DelegatorBot(SpeakerBot):
def __init__(self, token, delegation_patterns, loop=None):
"""
:param delegation_patterns: a list of (seeder, delegator) tuples.
"""
super(DelegatorBot, self).__init__(token, loop)
self._delegate_records = [p+({},) for p in delegation_patterns]
def handle(self, msg):
self._mic.send(msg)
for calculate_seed, make_coroutine_obj, dict in self._delegate_records:
id = calculate_seed(msg)
if id is None:
continue
if isinstance(id, collections.Hashable):
if id not in dict or dict[id].done():
c = make_coroutine_obj((self, msg, id))
if not asyncio.iscoroutine(c):
raise RuntimeError('You must produce a coroutine *object* as delegate.')
dict[id] = self._loop.create_task(c)
else:
c = make_coroutine_obj((self, msg, id))
self._loop.create_task(c)
|
class DelegatorBot(SpeakerBot):
def __init__(self, token, delegation_patterns, loop=None):
'''
:param delegation_patterns: a list of (seeder, delegator) tuples.
'''
pass
def handle(self, msg):
pass
| 3 | 1 | 13 | 2 | 9 | 2 | 4 | 0.16 | 1 | 2 | 0 | 1 | 2 | 1 | 2 | 92 | 27 | 5 | 19 | 6 | 16 | 3 | 18 | 6 | 15 | 6 | 3 | 4 | 7 |
4,475 |
AmanoTeam/amanobot
|
AmanoTeam_amanobot/amanobot/helper.py
|
amanobot.helper.IdleEventCoordinator
|
class IdleEventCoordinator():
def __init__(self, scheduler, timeout):
self._scheduler = scheduler
self._timeout_seconds = timeout
self._timeout_event = None
def refresh(self):
""" Refresh timeout timer """
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
# Timeout event has been popped from queue prematurely
except exception.EventNotFound:
pass
# Ensure a new event is scheduled always
finally:
self._timeout_event = self._scheduler.event_later(
self._timeout_seconds,
('_idle', {'seconds': self._timeout_seconds}))
def augment_on_message(self, handler):
"""
:return:
a function wrapping ``handler`` to refresh timer for every
non-event message
"""
def augmented(msg):
# Reset timer if this is an external message
is_event(msg) or self.refresh()
# Ignore timeout event that have been popped from queue prematurely
if flavor(msg) == '_idle' and msg is not self._timeout_event.data:
return
return handler(msg)
return augmented
def augment_on_close(self, handler):
"""
:return:
a function wrapping ``handler`` to cancel timeout event
"""
def augmented(ex):
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
self._timeout_event = None
# This closing may have been caused by my own timeout, in which case
# the timeout event can no longer be found in the scheduler.
except exception.EventNotFound:
self._timeout_event = None
return handler(ex)
return augmented
|
class IdleEventCoordinator():
def __init__(self, scheduler, timeout):
pass
def refresh(self):
''' Refresh timeout timer '''
pass
def augment_on_message(self, handler):
'''
:return:
a function wrapping ``handler`` to refresh timer for every
non-event message
'''
pass
def augmented(msg):
pass
def augment_on_close(self, handler):
'''
:return:
a function wrapping ``handler`` to cancel timeout event
'''
pass
def augmented(msg):
pass
| 7 | 3 | 12 | 1 | 7 | 3 | 2 | 0.5 | 0 | 1 | 1 | 1 | 4 | 3 | 4 | 4 | 55 | 7 | 32 | 10 | 25 | 16 | 29 | 10 | 22 | 3 | 0 | 2 | 11 |
4,476 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs._Directory
|
class _Directory(ioctl.Device):
SNAP_DESTROY = Control.IOW(15, btrfs_ioctl_vol_args)
SNAP_CREATE_V2 = Control.IOW(23, btrfs_ioctl_vol_args_v2)
|
class _Directory(ioctl.Device):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 2 | 0 | 0 |
4,477 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs._Volume
|
class _Volume(object):
""" Represents a subvolume. """
def __init__(self, fileSystem, rootid, generation, info):
""" Initialize. """
# logger.debug("Volume %d/%d: %s", rootid, generation, pretty(info))
self.fileSystem = fileSystem
self.id = rootid # id in BTRFS_ROOT_TREE_OBJECTID, also FS treeid for this volume
self.original_gen = info.otransid
self.current_gen = info.ctransid
# self.size = info.bytes_used
self.readOnly = bool(info.flags & BTRFS_ROOT_SUBVOL_RDONLY)
self.level = info.level
self.uuid = info.uuid
self.parent_uuid = info.parent_uuid
self.received_uuid = info.received_uuid
self.sent_gen = info.stransid
self.totalSize = None
self.exclusiveSize = None
self.info = info
self.links = {}
assert rootid not in self.fileSystem.volumes, rootid
self.fileSystem.volumes[rootid] = self
logger.debug("%s", self)
def _addLink(self, dirTree, dirID, dirSeq, dirPath, name):
""" Add tree reference and name. (Hardlink). """
logger.debug("Link %d-%d-%d '%s%s'", dirTree, dirID, dirSeq, dirPath, name)
# assert dirTree != 0, (dirTree, dirID, dirSeq, dirPath, name)
assert (dirTree, dirID, dirSeq) not in self.links, (dirTree, dirID, dirSeq)
self.links[(dirTree, dirID, dirSeq)] = (dirPath, name)
assert len(self.links) == 1, self.links # Cannot have multiple hardlinks to a directory
logger.debug("%s", self)
@property
def fullPath(self):
""" Return full butter path from butter root. """
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items():
try:
path = self.fileSystem.volumes[dirTree].fullPath
if path is not None:
return path + ("/" if path[-1] != "/" else "") + dirPath + name
except Exception:
logging.debug("Haven't imported %d yet", dirTree)
if self.id == BTRFS_FS_TREE_OBJECTID:
return "/"
else:
return None
@property
def linuxPaths(self):
""" Return full paths from linux root.
The first path returned will be the path through the top-most mount.
(Usually the root).
"""
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items():
for path in self.fileSystem.volumes[dirTree].linuxPaths:
yield path + "/" + dirPath + name
if self.fullPath in self.fileSystem.mounts:
yield self.fileSystem.mounts[self.fullPath]
def __str__(self):
""" String representation. """
# logger.debug("%d %d %d", self.gen, self.info.generation, self.info.inode.generation)
# logger.debug("%o %o", self.info.flags, self.info.inode.flags)
return """%4d '%s' (level:%d gen:%d total:%s exclusive:%s%s) %s
(parent:%s/%d received:%s/%d)
%s%s""" % (
self.id or -1,
# ", ".join([dirPath + name for (dirPath, name) in self.links.values()]),
self.fullPath,
self.level or -1,
self.current_gen or -1,
# self.size,
humanize(self.totalSize or -1),
humanize(self.exclusiveSize or -1),
" ro" if self.readOnly else "",
self.uuid,
self.parent_uuid, self.original_gen,
self.received_uuid, self.sent_gen,
"\n\t".join(self.linuxPaths),
# "\n\t" + pretty(self.__dict__),
"",
)
def destroy(self):
""" Delete this subvolume from the filesystem. """
path = next(iter(self.linuxPaths))
directory = _Directory(os.path.dirname(path))
with directory as device:
device.SNAP_DESTROY(name=str(os.path.basename(path)), )
def copy(self, path):
""" Make another snapshot of this into dirName. """
directoryPath = os.path.dirname(path)
if not os.path.exists(directoryPath):
os.makedirs(directoryPath)
logger.debug('Create copy of %s in %s', os.path.basename(path), directoryPath)
with self._snapshot() as source, _Directory(directoryPath) as dest:
dest.SNAP_CREATE_V2(
flags=BTRFS_SUBVOL_RDONLY,
name=str(os.path.basename(path)),
fd=source.fd,
)
with SnapShot(path) as destShot:
flags = destShot.SUBVOL_GETFLAGS()
destShot.SUBVOL_SETFLAGS(flags=flags.flags & ~BTRFS_SUBVOL_RDONLY)
destShot.SET_RECEIVED_SUBVOL(
uuid=self.received_uuid or self.uuid,
stransid=self.sent_gen or self.current_gen,
stime=timeOrNone(self.info.stime) or timeOrNone(self.info.ctime) or 0,
flags=0,
)
destShot.SUBVOL_SETFLAGS(flags=flags.flags)
def _snapshot(self):
path = next(iter(self.linuxPaths))
return SnapShot(path)
|
class _Volume(object):
''' Represents a subvolume. '''
def __init__(self, fileSystem, rootid, generation, info):
''' Initialize. '''
pass
def _addLink(self, dirTree, dirID, dirSeq, dirPath, name):
''' Add tree reference and name. (Hardlink). '''
pass
@property
def fullPath(self):
''' Return full butter path from butter root. '''
pass
@property
def linuxPaths(self):
''' Return full paths from linux root.
The first path returned will be the path through the top-most mount.
(Usually the root).
'''
pass
def __str__(self):
''' String representation. '''
pass
def destroy(self):
''' Delete this subvolume from the filesystem. '''
pass
def copy(self, path):
''' Make another snapshot of this into dirName. '''
pass
def _snapshot(self):
pass
| 11 | 8 | 15 | 2 | 11 | 3 | 2 | 0.23 | 1 | 5 | 2 | 0 | 8 | 14 | 8 | 8 | 131 | 21 | 91 | 37 | 80 | 21 | 64 | 32 | 55 | 6 | 1 | 3 | 18 |
4,478 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl.Buffer
|
class Buffer:
""" Contains bytes and an offset. """
def __init__(self, buf, offset=0, newLength=None):
""" Initialize. """
self.buf = buf
self.offset = offset
self._len = (newLength + offset) if newLength else len(buf)
def read(self, structure):
""" Read and advance. """
start = self.offset
self.skip(structure.size)
return structure.read(self.buf, start)
def skip(self, length):
""" Advance. """
self.offset += length
def readView(self, newLength=None):
""" Return a view of the next newLength bytes, and skip it. """
if newLength is None:
newLength = self.len
result = self.peekView(newLength)
self.skip(newLength)
return result
def peekView(self, newLength):
""" Return a view of the next newLength bytes. """
# Note: In Python 2.7, memoryviews can't be written to
# by the struct module. (BUG)
return memoryview(self.buf)[self.offset:self.offset + newLength]
def readBuffer(self, newLength):
""" Read next chunk as another buffer. """
result = Buffer(self.buf, self.offset, newLength)
self.skip(newLength)
return result
@property
def len(self):
""" Count of remaining bytes. """
return self._len - self.offset
def __len__(self):
""" Count of remaining bytes. """
return self._len - self.offset
|
class Buffer:
''' Contains bytes and an offset. '''
def __init__(self, buf, offset=0, newLength=None):
''' Initialize. '''
pass
def read(self, structure):
''' Read and advance. '''
pass
def skip(self, length):
''' Advance. '''
pass
def readView(self, newLength=None):
''' Return a view of the next newLength bytes, and skip it. '''
pass
def peekView(self, newLength):
''' Return a view of the next newLength bytes. '''
pass
def readBuffer(self, newLength):
''' Read next chunk as another buffer. '''
pass
@property
def len(self):
''' Count of remaining bytes. '''
pass
def __len__(self):
''' Count of remaining bytes. '''
pass
| 10 | 9 | 5 | 0 | 3 | 1 | 1 | 0.39 | 0 | 1 | 0 | 0 | 8 | 3 | 8 | 8 | 48 | 9 | 28 | 16 | 18 | 11 | 27 | 15 | 18 | 2 | 0 | 1 | 10 |
4,479 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl.t
|
class t:
""" Type definitions for translating linux C headers to Python struct format values. """
(s8, s16, s32, s64) = 'bhlq'
(u8, u16, u32, u64) = 'BHLQ'
(le16, le32, le64) = (u16, u32, u64) # Works on Linux x86
char = 'c'
max_u32 = (1 << 32) - 1
max_u64 = (1 << 64) - 1
@staticmethod
def writeChar(value):
""" Write a single-character string as a one-byte (u8) number. """
return 0 if value is None else ord(value[0])
@staticmethod
def writeString(data):
""" Write a string as null-terminated c string (bytes). """
if data is None:
return chr(0)
return data.encode('utf-8') + chr(0)
@staticmethod
def readString(data):
""" Read a null-terminated (c) string. """
# CAUTION: Great for strings, horrible for buffers!
return data.decode('utf-8').partition(chr(0))[0]
@staticmethod
def readBuffer(data):
""" Trim zero bytes in buffer. """
# CAUTION: Great for strings, horrible for buffers!
return data.rstrip(chr(0))
|
class t:
''' Type definitions for translating linux C headers to Python struct format values. '''
@staticmethod
def writeChar(value):
''' Write a single-character string as a one-byte (u8) number. '''
pass
@staticmethod
def writeString(data):
''' Write a string as null-terminated c string (bytes). '''
pass
@staticmethod
def readString(data):
''' Read a null-terminated (c) string. '''
pass
@staticmethod
def readBuffer(data):
''' Trim zero bytes in buffer. '''
pass
| 9 | 5 | 4 | 0 | 3 | 2 | 2 | 0.38 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 | 37 | 9 | 21 | 15 | 12 | 8 | 17 | 11 | 12 | 2 | 0 | 1 | 6 |
4,480 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl.Device
|
class Device(object):
""" Context manager for a linux file descriptor for a file or device special file.
Opening and closing is handled by the Python "with" statement.
"""
def __init__(self, path, flags=os.O_RDONLY):
""" Initialize. """
self.path = path
self.fd = None
self.flags = flags
def __enter__(self):
""" Open. """
self.fd = os.open(self.path, self.flags)
return self
def __exit__(self, exceptionType, exception, trace):
""" Close. """
os.close(self.fd)
self.fd = None
|
class Device(object):
''' Context manager for a linux file descriptor for a file or device special file.
Opening and closing is handled by the Python "with" statement.
'''
def __init__(self, path, flags=os.O_RDONLY):
''' Initialize. '''
pass
def __enter__(self):
''' Open. '''
pass
def __exit__(self, exceptionType, exception, trace):
''' Close. '''
pass
| 4 | 4 | 4 | 0 | 3 | 1 | 1 | 0.55 | 1 | 0 | 0 | 3 | 3 | 3 | 3 | 3 | 23 | 6 | 11 | 7 | 7 | 6 | 11 | 7 | 7 | 1 | 1 | 0 | 3 |
4,481 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/progress.py
|
buttersink.progress.DisplayProgress
|
class DisplayProgress(object):
""" Class to display Mbs progress on tty. """
def __init__(self, total=None, chunkName=None, parent=None):
""" Initialize. """
self.startTime = None
self.offset = None
self.total = total
self.name = chunkName
self.parent = parent
self.output = sys.stderr
def __enter__(self):
""" For with statement. """
self.open()
def open(self):
""" Reset time and counts. """
self.startTime = datetime.datetime.now()
self.offset = 0
return self
def __exit__(self, exceptionType, exceptionValue, traceback):
""" For with statement. """
self.close()
return False
def update(self, sent):
""" Update self and parent with intermediate progress. """
self.offset = sent
now = datetime.datetime.now()
elapsed = (now - self.startTime).total_seconds()
if elapsed > 0:
mbps = (sent * 8 / (10 ** 6)) / elapsed
else:
mbps = None
self._display(sent, now, self.name, mbps)
def _display(self, sent, now, chunk, mbps):
""" Display intermediate progress. """
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent <= self.total:
eta = (self.total - sent) * elapsed.total_seconds() / sent
eta = datetime.timedelta(seconds=eta)
else:
eta = None
self.output.write(
"\r %s: Sent %s%s%s ETA: %s (%s) %s%20s\r" % (
elapsed,
util.humanize(sent),
"" if self.total is None else " of %s" % (util.humanize(self.total),),
"" if self.total is None else " (%d%%)" % (int(100 * sent / self.total),),
eta,
"" if not mbps else "%.3g Mbps " % (mbps,),
chunk or "",
" ",
)
)
self.output.flush()
def close(self):
""" Stop overwriting display, or update parent. """
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
self.output.write("\n")
self.output.flush()
|
class DisplayProgress(object):
''' Class to display Mbs progress on tty. '''
def __init__(self, total=None, chunkName=None, parent=None):
''' Initialize. '''
pass
def __enter__(self):
''' For with statement. '''
pass
def open(self):
''' Reset time and counts. '''
pass
def __exit__(self, exceptionType, exceptionValue, traceback):
''' For with statement. '''
pass
def update(self, sent):
''' Update self and parent with intermediate progress. '''
pass
def _display(self, sent, now, chunk, mbps):
''' Display intermediate progress. '''
pass
def close(self):
''' Stop overwriting display, or update parent. '''
pass
| 8 | 8 | 10 | 1 | 8 | 1 | 2 | 0.15 | 1 | 3 | 0 | 1 | 7 | 6 | 7 | 7 | 78 | 15 | 55 | 19 | 47 | 8 | 42 | 19 | 34 | 6 | 1 | 1 | 14 |
4,482 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl._SkipType
|
class _SkipType:
def popValue(self, argList):
return None
def yieldArgs(self, arg):
if False:
yield None
|
class _SkipType:
def popValue(self, argList):
pass
def yieldArgs(self, arg):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 2 | 0.17 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 2 | 6 | 3 | 3 | 1 | 6 | 3 | 3 | 2 | 0 | 1 | 3 |
4,483 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/BestDiffs.py
|
buttersink.BestDiffs.BestDiffs
|
class BestDiffs:
""" This analyzes and stores an optimal network (tree).
The nodes are the desired (or intermediate) volumes.
The directed edges are diffs from an available sink.
"""
def __init__(self, volumes, delete=False, measureSize=True):
""" Initialize.
volumes are the required snapshots.
"""
self.nodes = {volume: _Node(volume, False) for volume in volumes}
self.dest = None
self.delete = delete
self.measureSize = measureSize
def analyze(self, chunkSize, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True
# Use destination (already uploaded) edges first
sinks = list(sinks)
sinks.reverse()
self.dest = sinks[0]
def currentSize():
return sum([
n.diffSize
for n in self.nodes.values()
if n.diff is not None and n.diff.sink != self.dest
])
while True:
self._analyzeDontMeasure(chunkSize, measureSize, *sinks)
if not measureSize:
return
estimatedSize = currentSize()
# logger.info("Measuring any estimated diffs")
for node in self.nodes.values():
edge = node.diff
if edge is not None and edge.sink != self.dest and edge.sizeIsEstimated:
edge.sink.measureSize(edge, chunkSize)
actualSize = currentSize()
logger.info(
"measured size (%s), estimated size (%s)",
humanize(actualSize), humanize(estimatedSize),
)
if actualSize <= 1.2 * estimatedSize:
return
def _analyzeDontMeasure(self, chunkSize, willMeasureLater, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
nodes = [None]
height = 1
def sortKey(node):
if node is None:
return None
return (node.intermediate, self._totalSize(node))
while len(nodes) > 0:
logger.debug("Analyzing %d nodes for height %d...", len(nodes), height)
nodes.sort(key=sortKey)
for fromNode in nodes:
if self._height(fromNode) >= height:
continue
if fromNode is not None and fromNode.diffSize is None:
continue
fromVol = fromNode.volume if fromNode else None
logger.debug("Following edges from %s", fromVol)
for sink in sinks:
# logger.debug(
# "Listing edges in %s",
# sink
# )
for edge in sink.getEdges(fromVol):
toVol = edge.toVol
# logger.debug("Edge: %s", edge)
# Skip any edges already in the destination
if sink != self.dest and self.dest.hasEdge(edge):
continue
if toVol in self.nodes:
toNode = self.nodes[toVol]
# Don't transfer any edges we won't need in the destination
# elif sink != self.dest:
# logger.debug("Won't transfer unnecessary %s", edge)
# continue
else:
toNode = _Node(toVol, True)
self.nodes[toVol] = toNode
logger.debug("Considering %s", edge)
edgeSize = edge.size
if edge.sizeIsEstimated:
if willMeasureLater:
# Slight preference for accurate sizes
edgeSize *= 1.2
else:
# Large preference for accurate sizes
edgeSize *= 2
newCost = self._cost(sink, edgeSize, fromNode, height)
if toNode.diff is None:
oldCost = None
else:
oldCost = self._cost(
toNode.sink,
toNode.diffSize,
self._getNode(toNode.previous),
self._height(toNode)
)
# Don't use a more-expensive path
if oldCost is not None and oldCost <= newCost:
continue
# Don't create circular paths
if self._wouldLoop(fromVol, toVol):
# logger.debug("Ignoring looping edge: %s", toVol.display(sink))
continue
# if measureSize and sink != self.dest and edge.sizeIsEstimated:
# sink.measureSize(edge, chunkSize)
# newCost = self._cost(sink, edge.size, fromSize, height)
# if oldCost is not None and oldCost <= newCost:
# continue
logger.debug(
"Replacing edge (%s -> %s cost)\n%s",
humanize(oldCost),
humanize(newCost),
toNode.display(sink)
)
# logger.debug("Cost elements: %s", dict(
# sink=str(sink),
# edgeSize=humanize(edgeSize),
# fromSize=humanize(fromSize),
# height=height,
# ))
toNode.diff = edge
nodes = [node for node in self.nodes.values() if self._height(node) == height]
height += 1
self._prune()
for node in self.nodes.values():
node.height = self._height(node)
if node.diff is None:
logger.error(
"No source diffs for %s",
node.volume.display(sinks[-1], detail="line"),
)
def _getNode(self, vol):
return self.nodes[vol] if vol is not None else None
def _height(self, node):
if node is None:
return 0
else:
return 1 + self._height(self._getNode(node.previous))
def _totalSize(self, node):
if node is None:
return 0
prevSize = self._totalSize(self._getNode(node.previous))
return (node.diffSize or 0) + prevSize
def _wouldLoop(self, fromVol, toVol):
if toVol is None:
return False
while fromVol is not None:
if fromVol == toVol:
return True
fromVol = self.nodes[fromVol].previous
return False
def iterDiffs(self):
""" Return all diffs used in optimal network. """
nodes = self.nodes.values()
nodes.sort(key=lambda node: self._height(node))
for node in nodes:
yield node.diff
# yield { 'from': node.previous, 'to': node.uuid, 'sink': node.diffSink,
def summary(self):
""" Return summary count and size in a dictionary. """
return _Node.summary(self.nodes.values())
def _prune(self):
""" Get rid of all intermediate nodes that aren't needed. """
done = False
while not done:
done = True
for node in [node for node in self.nodes.values() if node.intermediate]:
if not [dep for dep in self.nodes.values() if dep.previous == node.volume]:
# logger.debug("Removing unnecessary node %s", node)
del self.nodes[node.volume]
done = False
def _cost(self, sink, size, prevNode, height):
cost = 0
prevSize = self._totalSize(prevNode)
# Transfer
if sink != self.dest:
cost += size
if prevNode is not None and prevNode.intermediate and prevNode.sink != self.dest:
cost += prevSize
# Storage
if sink != self.dest or self.delete:
cost += size / 16
# Corruption risk
if self.dest.isDiffStore:
cost += (prevSize + size) * (2 ** (height - 6))
logger.debug(
"_cost=%s (%s %s %s %d)",
humanize(cost), sink, humanize(size), humanize(prevSize), height,
)
return cost
|
class BestDiffs:
''' This analyzes and stores an optimal network (tree).
The nodes are the desired (or intermediate) volumes.
The directed edges are diffs from an available sink.
'''
def __init__(self, volumes, delete=False, measureSize=True):
''' Initialize.
volumes are the required snapshots.
'''
pass
def analyze(self, chunkSize, *sinks):
''' Figure out the best diffs to use to reach all our required volumes. '''
pass
def currentSize():
pass
def _analyzeDontMeasure(self, chunkSize, willMeasureLater, *sinks):
''' Figure out the best diffs to use to reach all our required volumes. '''
pass
def sortKey(node):
pass
def _getNode(self, vol):
pass
def _height(self, node):
pass
def _totalSize(self, node):
pass
def _wouldLoop(self, fromVol, toVol):
pass
def iterDiffs(self):
''' Return all diffs used in optimal network. '''
pass
def summary(self):
''' Return summary count and size in a dictionary. '''
pass
def _prune(self):
''' Get rid of all intermediate nodes that aren't needed. '''
pass
def _cost(self, sink, size, prevNode, height):
pass
| 14 | 7 | 19 | 4 | 12 | 3 | 4 | 0.29 | 0 | 2 | 1 | 0 | 11 | 4 | 11 | 11 | 258 | 60 | 153 | 42 | 139 | 45 | 126 | 42 | 112 | 17 | 0 | 6 | 52 |
4,484 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/BestDiffs.py
|
buttersink.BestDiffs.Bunch
|
class Bunch(object):
""" Simple mutable data record. """
def __init__(self, **kwds):
""" Initialize. """
self.__dict__.update(kwds)
|
class Bunch(object):
''' Simple mutable data record. '''
def __init__(self, **kwds):
''' Initialize. '''
pass
| 2 | 2 | 3 | 0 | 2 | 1 | 1 | 0.67 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 2 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
4,485 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl._TypeWriter
|
class _TypeWriter:
def __init__(self, default, reader=None, writer=None):
self._default = default
self._writer = writer or (lambda x: x)
self._reader = reader or (lambda x: x)
def popValue(self, argList):
return self._reader(argList.pop())
def yieldArgs(self, arg):
yield self._writer(arg) or self._default
|
class _TypeWriter:
def __init__(self, default, reader=None, writer=None):
pass
def popValue(self, argList):
pass
def yieldArgs(self, arg):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 12 | 3 | 9 | 7 | 5 | 0 | 9 | 7 | 5 | 1 | 0 | 0 | 3 |
4,486 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/util.py
|
buttersink.util.DefaultList
|
class DefaultList(list):
""" list that automatically inserts None for missing items. """
def __setitem__(self, index, value):
""" Set item. """
if len(self) > index:
return list.__setitem__(self, index, value)
if len(self) < index:
self.extend([None] * (index - len(self)))
list.append(self, value)
def __getitem__(self, index):
""" Set item. """
if index >= len(self):
return None
return list.__getitem__(self, index)
|
class DefaultList(list):
''' list that automatically inserts None for missing items. '''
def __setitem__(self, index, value):
''' Set item. '''
pass
def __getitem__(self, index):
''' Set item. '''
pass
| 3 | 3 | 6 | 0 | 5 | 1 | 3 | 0.27 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 35 | 17 | 3 | 11 | 3 | 8 | 3 | 11 | 3 | 8 | 3 | 2 | 1 | 5 |
4,487 |
AmesCornish/buttersink
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore.StoreProxyServer
|
class StoreProxyServer(object):
""" Runs a ButterStore and responds to queries over ssh.
Use in a 'with' statement.
"""
def __init__(self, path, mode):
""" Initialize. """
logger.debug("Proxy(%s) %s", mode, path)
self.path = path
self.mode = mode
self.butterStore = None
self.running = False
self.toObj = None
self.toDict = None
self.stream = None
def __enter__(self):
""" Enter 'with' statement. """
return self
def __exit__(self, exceptionType, exception, trace):
""" Exit 'with' statement. """
try:
self._close()
except Exception as error:
if exceptionType is None:
raise
else:
logger.info("Error on close: %s", error)
return False
def _open(self, stream):
if self.stream is not None:
logger.warn("%s not closed.", self.stream)
self._close()
self.stream = stream
self.stream.__enter__()
def _close(self):
if self.stream is None:
return
try:
self.stream.__exit__(None, None, None)
finally:
self.stream = None
def run(self):
""" Run the server. Returns with system error code. """
normalized = os.path.normpath(
self.path) + ("/" if self.path.endswith("/") else "")
if self.path != normalized:
sys.stderr.write("Please use full path '%s'" % (normalized,))
return -1
self.butterStore = ButterStore.ButterStore(
None, self.path, self.mode, dryrun=False)
# self.butterStore.ignoreExtraVolumes = True
self.toObj = _Arg2Obj(self.butterStore)
self.toDict = _Obj2Dict()
self.running = True
with self.butterStore:
with self:
while self.running:
self._processCommand()
return 0
def _errorInfo(self, command, error):
trace = traceback.format_exc()
trace = trace.splitlines()[-3].strip()
# Emit into local syslog, but let remote display to user
logger.debug('%s in %s', str(error), trace)
return dict(
error=str(error),
errorType=type(error).__name__,
command=command,
server=True,
traceback=trace,
)
def _sendResult(self, result):
""" Send parseable json result of command. """
# logger.debug("Result: %s", result)
try:
result = json.dumps(result)
except Exception as error:
result = json.dumps(self._errorInfo(command, error))
sys.stdout.write(result)
sys.stdout.write("\n")
sys.stdout.flush()
def _errorMessage(self, message):
sys.stderr.write(str(message))
sys.stderr.write("\n")
sys.stderr.flush()
def _processCommand(self):
commandLine = sys.stdin.readline().rstrip('\n').split(" ")
commandLine = [urllib.unquote_plus(c) for c in commandLine]
command = commandLine[0]
# logger.debug("Command: '%s'", commandLine)
if not command:
self._errorMessage("No more commands -- terminating.")
self.running = False
return
try:
if command not in commands:
raise Exception("Unknown command")
method = getattr(self, commands[command])
fn = method.__get__(self, StoreProxyServer)
result = fn(*commandLine[1:])
if result is None:
result = dict(command=command, success=True)
except Exception as error:
# logger.exception("Failed %s", command)
result = self._errorInfo(command, error)
self._sendResult(result)
@command('quit', 'r')
def quit(self):
""" Quit the server. """
self.running = False
return dict(message="Quitting")
@command('version', 'r')
def version(self):
""" Return kernel and btrfs version. """
return dict(
buttersink=theVersion,
btrfs=self.butterStore.butter.btrfsVersion,
linux=platform.platform(),
)
@command('send', 'r')
def send(self, diffTo, diffFrom):
""" Do a btrfs send. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.send(diff))
@command('receive', 'a')
def receive(self, path, diffTo, diffFrom):
""" Receive a btrfs diff. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ]))
@command('write', 'r')
def streamWrite(self, size):
""" Send or receive a chunk of data.
:arg size: Amount of data. 0 indicates EOT.
"""
size = int(size)
if size == 0:
self._close()
return
self._sendResult(dict(message="writing...", stream=True, size=size))
data = sys.stdin.read(size)
self.stream.write(data)
@command('read', 'r')
def streamRead(self, size):
""" Send or receive a chunk of data.
:arg size: Amount of data requested.
"""
size = int(size)
data = self.stream.read(size)
size = len(data)
if size == 0:
self._close()
return dict(message="Finished", size=0)
self._sendResult(dict(message="reading...", stream=True, size=size))
sys.stdout.write(data)
@command('volumes', 'r')
def fillVolumesAndPaths(self):
""" Get all volumes for initialization. """
return [
(self.toDict.vol(vol), paths)
for vol, paths in self.butterStore.paths.items()
]
@command('edges', 'r')
def getEdges(self, fromVol):
""" Return the edges available from fromVol. """
return [self.toDict.diff(d) for d in self.butterStore.getEdges(self.toObj.vol(fromVol))]
@command('measure', 'r')
def measureSize(self, diffTo, diffFrom, estimatedSize, chunkSize, isInteractive):
""" Spend some time to get an accurate size. """
diff = self.toObj.diff(diffTo, diffFrom, estimatedSize)
isInteractive = self.toObj.bool(isInteractive)
self.butterStore.showProgress = None if isInteractive else False
self.butterStore.measureSize(diff, int(chunkSize))
return self.toDict.diff(diff)
@command('keep', 'r')
def keep(self, diffTo, diffFrom):
""" Mark this diff (or volume) to be kept in path. """
diff = self.toObj.diff(diffTo, diffFrom)
self.butterStore.keep(diff)
@command('delete', 'w')
def deleteUnused(self):
""" Delete any old snapshots in path, if not kept. """
self.butterStore.deleteUnused()
@command('clean', 'w')
def deletePartials(self):
""" Delete any old partial uploads/downloads in path. """
self.butterStore.deletePartials()
@command('listDelete', 'r')
def listUnused(self):
""" Delete any old snapshots in path, if not kept. """
self.butterStore.deleteUnused(dryrun=True)
@command('listClean', 'r')
def listPartials(self):
""" Delete any old partial uploads/downloads in path. """
self.butterStore.deletePartials(dryrun=True)
@command('info', 'a')
def receiveInfo(self, path):
""" Receive volume info. """
self.stream = open(path, "w")
|
class StoreProxyServer(object):
''' Runs a ButterStore and responds to queries over ssh.
Use in a 'with' statement.
'''
def __init__(self, path, mode):
''' Initialize. '''
pass
def __enter__(self):
''' Enter 'with' statement. '''
pass
def __exit__(self, exceptionType, exception, trace):
''' Exit 'with' statement. '''
pass
def _open(self, stream):
pass
def _close(self):
pass
def run(self):
''' Run the server. Returns with system error code. '''
pass
def _errorInfo(self, command, error):
pass
def _sendResult(self, result):
''' Send parseable json result of command. '''
pass
def _errorMessage(self, message):
pass
def _processCommand(self):
pass
@command('quit', 'r')
def quit(self):
''' Quit the server. '''
pass
@command('version', 'r')
def version(self):
''' Return kernel and btrfs version. '''
pass
@command('send', 'r')
def send(self, diffTo, diffFrom):
''' Do a btrfs send. '''
pass
@command('receive', 'a')
def receive(self, path, diffTo, diffFrom):
''' Receive a btrfs diff. '''
pass
@command('write', 'r')
def streamWrite(self, size):
''' Send or receive a chunk of data.
:arg size: Amount of data. 0 indicates EOT.
'''
pass
@command('read', 'r')
def streamRead(self, size):
''' Send or receive a chunk of data.
:arg size: Amount of data requested.
'''
pass
@command('volumes', 'r')
def fillVolumesAndPaths(self):
''' Get all volumes for initialization. '''
pass
@command('edges', 'r')
def getEdges(self, fromVol):
''' Return the edges available from fromVol. '''
pass
@command('measure', 'r')
def measureSize(self, diffTo, diffFrom, estimatedSize, chunkSize, isInteractive):
''' Spend some time to get an accurate size. '''
pass
@command('keep', 'r')
def keep(self, diffTo, diffFrom):
''' Mark this diff (or volume) to be kept in path. '''
pass
@command('delete', 'w')
def deleteUnused(self):
''' Delete any old snapshots in path, if not kept. '''
pass
@command('clean', 'w')
def deletePartials(self):
''' Delete any old partial uploads/downloads in path. '''
pass
@command('listDelete', 'r')
def listUnused(self):
''' Delete any old snapshots in path, if not kept. '''
pass
@command('listClean', 'r')
def listPartials(self):
''' Delete any old partial uploads/downloads in path. '''
pass
@command('info', 'a')
def receiveInfo(self, path):
''' Receive volume info. '''
pass
| 41 | 21 | 8 | 1 | 6 | 1 | 2 | 0.2 | 1 | 8 | 3 | 0 | 25 | 7 | 25 | 25 | 240 | 45 | 163 | 64 | 122 | 32 | 133 | 46 | 107 | 5 | 1 | 3 | 40 |
4,488 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/send.py
|
buttersink.send.ParseException
|
class ParseException(Exception):
""" Dedicated Exception class. """
pass
|
class ParseException(Exception):
''' Dedicated Exception class. '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 5 | 2 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
4,489 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl.Control
|
class Control:
""" Callable linux io control (ioctl). """
def __init__(self, direction, op, structure):
""" Initialize. """
self.structure = structure
size = structure.size if structure else 0
self.ioc = self._iocNumber(direction, self.magic, op, size)
def __call__(self, device, **args):
""" Execute the call. """
if device.fd is None:
raise Exception("Device hasn't been successfully opened. Use 'with' statement.")
try:
if self.structure is not None:
args = self.structure.write(args)
# log.write(args)
ret = fcntl.ioctl(device.fd, self.ioc, args, True)
# log.write(args)
assert ret == 0, ret
return self.structure.read(args)
else:
ret = fcntl.ioctl(device.fd, self.ioc)
assert ret == 0, ret
except IOError as error:
error.filename = device.path
raise
@staticmethod
def _iocNumber(dir, type, nr, size):
return dir << DIRSHIFT | \
type << TYPESHIFT | \
nr << NRSHIFT | \
size << SIZESHIFT
@classmethod
def _IOC(cls, dir, op, structure=None):
""" Encode an ioctl id. """
control = cls(dir, op, structure)
def do(dev, **args):
return control(dev, **args)
return do
@classmethod
def IO(cls, op):
""" Returns an ioctl Device method with no arguments. """
return cls._IOC(NONE, op)
@classmethod
def IOW(cls, op, structure):
""" Returns an ioctl Device method with WRITE arguments. """
return cls._IOC(WRITE, op, structure)
@classmethod
def IOWR(cls, op, structure):
""" Returns an ioctl Device method with READ and WRITE arguments. """
return cls._IOC(READ | WRITE, op, structure)
@classmethod
def IOR(cls, op, structure):
""" Returns an ioctl Device method with READ arguments. """
return cls._IOC(READ, op, structure)
|
class Control:
''' Callable linux io control (ioctl). '''
def __init__(self, direction, op, structure):
''' Initialize. '''
pass
def __call__(self, device, **args):
''' Execute the call. '''
pass
@staticmethod
def _iocNumber(dir, type, nr, size):
pass
@classmethod
def _IOC(cls, dir, op, structure=None):
''' Encode an ioctl id. '''
pass
def do(dev, **args):
pass
@classmethod
def IO(cls, op):
''' Returns an ioctl Device method with no arguments. '''
pass
@classmethod
def IOW(cls, op, structure):
''' Returns an ioctl Device method with WRITE arguments. '''
pass
@classmethod
def IOWR(cls, op, structure):
''' Returns an ioctl Device method with READ and WRITE arguments. '''
pass
@classmethod
def IOR(cls, op, structure):
''' Returns an ioctl Device method with READ arguments. '''
pass
| 16 | 8 | 6 | 0 | 4 | 1 | 1 | 0.23 | 0 | 1 | 0 | 1 | 2 | 2 | 8 | 8 | 65 | 11 | 44 | 22 | 28 | 10 | 34 | 15 | 24 | 4 | 0 | 2 | 13 |
4,490 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/ioctl.py
|
buttersink.ioctl.Structure
|
class Structure:
""" Model a C struct.
Encapsulates a struct format with named item values.
structure fields are (typeDef, name, len=1) arguments.
typeDef can be a string or a structure itself.
Example Structures:
>>> s1 = Structure((t.char, 'char1'))
>>> s2 = Structure(
... (t.u16, 'foo'),
... (t.u8, 'bar', 8, t.readString, t.writeString),
... (s1, 'foobar'),
... )
>>> s2.fmt
'H8sc'
>>> s2.size
11
Instance variables:
>>> s2._Tuple(1,2,3).__dict__
OrderedDict([('foo', 1), ('bar', 2), ('foobar', 3)])
>>> s2._packed
True
>>> s2._types.keys()
['foo', 'bar', 'foobar']
Using a Structure:
>>> myValues = dict(foo=8, bar=u"hola", foobar=dict(char1='a'))
>>> data = s2.write(myValues)
>>> data
array('B', [8, 0, 104, 111, 108, 97, 0, 0, 0, 0, 97])
>>> values = s2.read(data)
>>> values
StructureTuple(foo=8, bar=u'hola', foobar=StructureTuple(char1='a'))
>>> values.foo
8
>>> values.foobar.char1
'a'
"""
def __init__(self, *fields, **keyArgs):
""" Initialize. """
(names, formats, types) = unzip([self._parseDefinition(*f) for f in fields])
self._Tuple = collections.namedtuple("StructureTuple", names)
self._fmt = "".join(formats)
self._packed = keyArgs.get('packed', True)
self._struct = struct.Struct("=" + self._fmt if self._packed else self._fmt)
self._types = collections.OrderedDict(zip(names, types))
@property
def size(self):
""" Total packed data size. """
return self._struct.size
@property
def fmt(self):
""" struct module format string without the leading byte-order character. """
return self._fmt
# This produces a dictionary of { fmtChar: defaultValue }
defaults = dict(itertools.chain(*[
[(fmtChar, defaultValue) for fmtChar in s]
for (s, defaultValue) in [
("sp", ""),
("bBhHiIlLqQfdP", 0),
("?", False),
("c", chr(0)),
]]))
skipType = _SkipType()
@staticmethod
def _parseDefinition(typeDef, name, len=1, reader=None, writer=None):
""" Return (name, format, type) for field.
type.popValue() and type.yieldArgs() must be implemented.
"""
if isinstance(typeDef, Structure):
return (name, typeDef.fmt, typeDef)
if len != 1:
size = struct.calcsize(typeDef)
if typeDef not in "xspP":
typeDef = 's'
typeDef = str(len * size) + typeDef
fmtChar = typeDef[-1:]
if fmtChar == 'x':
typeObj = Structure.skipType
else:
typeObj = _TypeWriter(Structure.defaults[fmtChar], reader, writer)
return (name, typeDef, typeObj)
def yieldArgs(self, keyArgs):
try:
keyArgs = keyArgs._asdict() if keyArgs else {}
except AttributeError:
pass
logger.debug('Args: %s', keyArgs)
""" Take (nested) dict(s) of args to set, and return flat list of args. """
for (name, typeObj) in self._types.items():
logger.debug('Yielding %s: %s', name, typeObj)
for arg in typeObj.yieldArgs(keyArgs.get(name, None)):
yield arg
def write(self, keyArgs):
""" Write specified key arguments into data structure. """
# bytearray doesn't work with fcntl
args = array.array('B', (0,) * self.size)
self._struct.pack_into(args, 0, *list(self.yieldArgs(keyArgs)))
return args
def popValue(self, argList):
""" Take a flat arglist, and pop relevent values and return as a value or tuple. """
# return self._Tuple(*[name for (name, typeObj) in self._types.items()])
return self._Tuple(*[typeObj.popValue(argList) for (name, typeObj) in self._types.items()])
def read(self, data, offset=0):
""" Read data structure and return (nested) named tuple(s). """
if isinstance(data, Buffer):
return data.read(self)
try:
args = list(self._struct.unpack_from(data, offset))
except TypeError as error:
# Working around struct.unpack_from issue #10212
logger.debug("error: %s", error)
args = list(self._struct.unpack_from(str(bytearray(data)), offset))
args.reverse()
return self.popValue(args)
|
class Structure:
''' Model a C struct.
Encapsulates a struct format with named item values.
structure fields are (typeDef, name, len=1) arguments.
typeDef can be a string or a structure itself.
Example Structures:
>>> s1 = Structure((t.char, 'char1'))
>>> s2 = Structure(
... (t.u16, 'foo'),
... (t.u8, 'bar', 8, t.readString, t.writeString),
... (s1, 'foobar'),
... )
>>> s2.fmt
'H8sc'
>>> s2.size
11
Instance variables:
>>> s2._Tuple(1,2,3).__dict__
OrderedDict([('foo', 1), ('bar', 2), ('foobar', 3)])
>>> s2._packed
True
>>> s2._types.keys()
['foo', 'bar', 'foobar']
Using a Structure:
>>> myValues = dict(foo=8, bar=u"hola", foobar=dict(char1='a'))
>>> data = s2.write(myValues)
>>> data
array('B', [8, 0, 104, 111, 108, 97, 0, 0, 0, 0, 97])
>>> values = s2.read(data)
>>> values
StructureTuple(foo=8, bar=u'hola', foobar=StructureTuple(char1='a'))
>>> values.foo
8
>>> values.foobar.char1
'a'
'''
def __init__(self, *fields, **keyArgs):
''' Initialize. '''
pass
@property
def size(self):
''' Total packed data size. '''
pass
@property
def fmt(self):
''' struct module format string without the leading byte-order character. '''
pass
@staticmethod
def _parseDefinition(typeDef, name, len=1, reader=None, writer=None):
''' Return (name, format, type) for field.
type.popValue() and type.yieldArgs() must be implemented.
'''
pass
def yieldArgs(self, keyArgs):
pass
def write(self, keyArgs):
''' Write specified key arguments into data structure. '''
pass
def popValue(self, argList):
''' Take a flat arglist, and pop relevent values and return as a value or tuple. '''
pass
def read(self, data, offset=0):
''' Read data structure and return (nested) named tuple(s). '''
pass
| 12 | 8 | 9 | 1 | 6 | 2 | 2 | 0.77 | 0 | 10 | 2 | 0 | 7 | 5 | 8 | 8 | 140 | 27 | 64 | 29 | 52 | 49 | 53 | 24 | 44 | 5 | 0 | 2 | 19 |
4,491 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/btrfs.py
|
buttersink.btrfs.FileSystem
|
class FileSystem(ioctl.Device):
""" Mounted file system descriptor for ioctl actions. """
def __init__(self, path):
""" Initialize. """
super(FileSystem, self).__init__(path)
self.defaultID = None
self.devices = []
self.volumes = {}
self.mounts = {}
@property
def subvolumes(self):
""" Subvolumes contained in this mount. """
self.SYNC()
self._getDevices()
self._getRoots()
self._getMounts()
self._getUsage()
volumes = self.volumes.values()
volumes.sort(key=(lambda v: v.fullPath))
return volumes
def _rescanSizes(self, force=True):
""" Zero and recalculate quota sizes to subvolume sizes will be correct. """
status = self.QUOTA_CTL(cmd=BTRFS_QUOTA_CTL_ENABLE).status
logger.debug("CTL Status: %s", hex(status))
status = self.QUOTA_RESCAN_STATUS()
logger.debug("RESCAN Status: %s", status)
if not status.flags:
if not force:
return
self.QUOTA_RESCAN()
logger.warn("Waiting for btrfs quota usage scan...")
self.QUOTA_RESCAN_WAIT()
def _getDevices(self):
if self.devices:
return
fs = self.FS_INFO()
for i in xrange(1, fs.max_id + 1):
try:
dev = self.DEV_INFO(devid=i)
except IOError as error:
if error.errno == 19:
continue
raise
self.devices.append(dev.path)
def _getMounts(self):
# This is a "fake" device, created separately for each subvol
# See https://bugzilla.redhat.com/show_bug.cgi?id=711881
# myDevice = os.stat(self.path).st_dev
# myDevice = (os.major(myDevice), os.minor(myDevice))
if self.mounts:
return
if self.defaultID is None:
logger.warn("Default subvolume not identified")
defaultSubvol = ""
else:
defaultSubvol = self.volumes[self.defaultID].fullPath.rstrip("/")
logger.debug("Default subvolume: %s", defaultSubvol)
with open("/proc/self/mountinfo") as mtab:
for line in mtab:
# (dev, path, fs, opts, freq, passNum) = line.split() # /etc/mtab
(left, _, right) = line.partition(" - ")
(mountID, parentID, devIDs, subvol, path, mountOpts) = left.split()[:6]
(fs, dev, superOpts) = right.split()
if fs != "btrfs":
continue
if dev not in self.devices:
logger.debug(
"%s device (%s) not in %s devices (%s)",
path, dev, self.path, self.devices,
)
continue
self.mounts[subvol] = path
logger.debug("%s: %s", subvol, path)
Key = collections.namedtuple('Key', ('objectid', 'type', 'offset'))
Key.first = Key(
objectid=0,
type=0,
offset=0,
)
Key.last = Key(
objectid=BTRFS_LAST_FREE_OBJECTID,
type=t.max_u32,
offset=t.max_u64,
)
Key.next = (lambda key: FileSystem.Key(key.objectid, key.type, key.offset + 1))
def _walkTree(self, treeid):
key = FileSystem.Key.first
while True:
# Returned objects seem to be monotonically increasing in (objectid, type, offset)
# min and max values are *not* filters.
result = self.TREE_SEARCH(
key=dict(
tree_id=treeid,
min_type=key.type,
max_type=FileSystem.Key.last.type,
min_objectid=key.objectid,
max_objectid=FileSystem.Key.last.objectid,
min_offset=key.offset,
max_offset=FileSystem.Key.last.offset,
min_transid=0,
max_transid=t.max_u64,
nr_items=4096,
),
)
# logger.debug("Search key result: \n%s", pretty(result.key))
buf = ioctl.Buffer(result.buf)
results = result.key.nr_items
# logger.debug("Reading %d nodes from %d bytes", results, buf.len)
if results == 0:
break
for _ in xrange(results):
# assert buf.len >= btrfs_ioctl_search_header.size, buf.len
data = buf.read(btrfs_ioctl_search_header)
# logger.debug("Object %d: %s", i, pretty(data))
# assert buf.len >= data.len, (buf.len, data.len)
yield (data, buf.readBuffer(data.len))
key = FileSystem.Key(data.objectid, data.type, data.offset).next()
def _getRoots(self):
for (header, buf) in self._walkTree(BTRFS_ROOT_TREE_OBJECTID):
if header.type == objectTypeKeys['BTRFS_ROOT_BACKREF_KEY']:
info = buf.read(btrfs_root_ref)
name = buf.readView(info.name_len).tobytes()
directory = self.INO_LOOKUP(treeid=header.offset, objectid=info.dirid)
logger.debug("%s: %s %s", name, pretty(info), pretty(directory))
self.volumes[header.objectid]._addLink(
header.offset,
info.dirid,
info.sequence,
directory.name,
name,
)
elif header.type == objectTypeKeys['BTRFS_ROOT_ITEM_KEY']:
if header.len == btrfs_root_item.size:
info = buf.read(btrfs_root_item)
elif header.len == btrfs_root_item_v0.size:
info = buf.read(btrfs_root_item_v0)
else:
assert False, header.len
if (
(header.objectid >= BTRFS_FIRST_FREE_OBJECTID
and header.objectid <= BTRFS_LAST_FREE_OBJECTID)
or header.objectid == BTRFS_FS_TREE_OBJECTID
):
assert header.objectid not in self.volumes, header.objectid
self.volumes[header.objectid] = _Volume(
self,
header.objectid,
header.offset,
info,
)
elif header.type == objectTypeKeys['BTRFS_DIR_ITEM_KEY']:
info = buf.read(btrfs_dir_item)
name = buf.readView(info.name_len).tobytes()
if name == "default":
self.defaultID = info.location.objectid
logger.debug("Found dir '%s' is %d", name, self.defaultID)
def _getUsage(self):
try:
self._rescanSizes(False)
self._unsafeGetUsage()
except (IOError, _BtrfsError) as error:
logger.warn("%s", error)
self._rescanSizes()
self._unsafeGetUsage()
def _unsafeGetUsage(self):
for (header, buf) in self._walkTree(BTRFS_QUOTA_TREE_OBJECTID):
# logger.debug("%s %s", objectTypeNames[header.type], header)
if header.type == objectTypeKeys['BTRFS_QGROUP_INFO_KEY']:
data = btrfs_qgroup_info_item.read(buf)
try:
vol = self.volumes[header.offset]
vol.totalSize = data.referenced
vol.exclusiveSize = data.exclusive
if (
data.referenced < 0 or
data.exclusive < 0 or
data.referenced < data.exclusive
):
raise _BtrfsError(
"Btrfs returned corrupt size of %s (%s exclusive) for %s" %
(
humanize(vol.totalSize or -1),
humanize(vol.exclusiveSize or -1),
vol.fullPath,
)
)
except KeyError:
pass
elif header.type == objectTypeKeys['BTRFS_QGROUP_LIMIT_KEY']:
data = btrfs_qgroup_limit_item.read(buf)
elif header.type == objectTypeKeys['BTRFS_QGROUP_RELATION_KEY']:
data = None
else:
data = None
# logger.debug('%s', pretty(data))
def _getDevInfo(self):
return self.DEV_INFO(devid=1, uuid="")
def _getFSInfo(self):
return self.FS_INFO()
volid_struct = Structure(
(t.u64, 'id')
)
SYNC = Control.IO(8)
TREE_SEARCH = Control.IOWR(17, btrfs_ioctl_search_args)
INO_LOOKUP = Control.IOWR(18, btrfs_ioctl_ino_lookup_args)
DEFAULT_SUBVOL = Control.IOW(19, volid_struct)
DEV_INFO = Control.IOWR(30, btrfs_ioctl_dev_info_args)
FS_INFO = Control.IOR(31, btrfs_ioctl_fs_info_args)
QUOTA_CTL = Control.IOWR(40, btrfs_ioctl_quota_ctl_args)
QUOTA_RESCAN = Control.IOW(44, btrfs_ioctl_quota_rescan_args)
QUOTA_RESCAN_STATUS = Control.IOR(45, btrfs_ioctl_quota_rescan_args)
QUOTA_RESCAN_WAIT = Control.IO(46)
|
class FileSystem(ioctl.Device):
''' Mounted file system descriptor for ioctl actions. '''
def __init__(self, path):
''' Initialize. '''
pass
@property
def subvolumes(self):
''' Subvolumes contained in this mount. '''
pass
def _rescanSizes(self, force=True):
''' Zero and recalculate quota sizes to subvolume sizes will be correct. '''
pass
def _getDevices(self):
pass
def _getMounts(self):
pass
def _walkTree(self, treeid):
pass
def _getRoots(self):
pass
def _getUsage(self):
pass
def _unsafeGetUsage(self):
pass
def _getDevInfo(self):
pass
def _getFSInfo(self):
pass
| 13 | 4 | 19 | 3 | 15 | 1 | 4 | 0.09 | 1 | 7 | 4 | 0 | 11 | 4 | 11 | 14 | 260 | 48 | 194 | 55 | 181 | 18 | 133 | 51 | 121 | 9 | 2 | 4 | 40 |
4,492 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/S3Store.py
|
buttersink.S3Store._BotoProgress
|
class _BotoProgress(progress.DisplayProgress):
def __init__(self, total=None, chunkName=None, parent=None):
super(_BotoProgress, self).__init__(total, chunkName, parent)
self.numCallBacks = theProgressCount
def __call__(self, sent, total):
logger.debug("BotoProgress: %d/%d", sent, total)
self.total = total
self.update(sent)
@staticmethod
def botoArgs(self):
if self is not None:
return {'cb': self, 'num_cb': self.numCallBacks}
else:
return {'cb': None, 'num_cb': None}
|
class _BotoProgress(progress.DisplayProgress):
def __init__(self, total=None, chunkName=None, parent=None):
pass
def __call__(self, sent, total):
pass
@staticmethod
def botoArgs(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 2 | 3 | 10 | 17 | 3 | 14 | 7 | 9 | 0 | 12 | 6 | 8 | 2 | 2 | 1 | 4 |
4,493 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._Client
|
class _Client(object):
def __init__(self, host, mode, directory):
self._host = host
self._mode = mode
self._directory = directory
self._process = None
self.error = None
def _open(self):
""" Open connection to remote host. """
if self._process is not None:
return
cmd = [
'ssh',
self._host,
'sudo',
'buttersink',
'--server',
'--mode',
self._mode,
self._directory
]
logger.debug("Connecting with: %s", cmd)
self._process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stderr=sys.stderr,
# stdout=sys.stdout,
stdout=subprocess.PIPE,
)
version = self.version()
logger.info("Remote version: %s", version)
def _close(self):
""" Close connection to remote host. """
if self._process is None:
return
self.quit()
self._process.stdin.close()
logger.debug("Waiting for ssh process to finish...")
self._process.wait() # Wait for ssh session to finish.
# self._process.terminate()
# self._process.kill()
self._process = None
def _checkMode(self, name, mode):
modes = ["read-only", "append", "write"]
def value(mode):
return [s[0] for s in modes].index(mode)
allowedMode = value(self._mode)
requestedMode = value(mode)
if requestedMode > allowedMode:
raise Exception(
"%s connection does not allow %s method '%s'" %
(modes[allowedMode], modes[requestedMode], name)
)
def _getResult(self):
result = self._process.stdout.readline().rstrip("\n")
# logger.debug('Result: %s', result)
try:
result = json.loads(result)
except Exception:
# result += os.read(self._process.stdout.fileno(), 5)
# result += self._process.stdout.read()
logger.error(result)
raise Exception("Fatal remote ssh server error")
return result
def _sendCommand(self, *command):
if self.error is not None:
# logger.warn("Not sending %s because of %s", command, self.error)
return dict(error=self.error, message="Can't send command", command=command[0])
try:
command = ['None' if c is None else urllib.quote_plus(str(c), '/') for c in command]
except Exception:
raise Exception("Can't send '%s' over ssh." % (command,))
# logger.debug("Command line: %s", command)
commandLine = " ".join(command) + "\n"
try:
self._process.stdin.write(commandLine)
result = self._getResult()
except Exception as error:
self.error = error
raise
if result and 'error' in result:
raise Exception(result)
return result
@classmethod
def _addMethod(cls, method, name, mode):
def fn(self, *args):
self._checkMode(name, mode)
return self._sendCommand(name, *args)
setattr(cls, method, fn)
|
class _Client(object):
def __init__(self, host, mode, directory):
pass
def _open(self):
''' Open connection to remote host. '''
pass
def _close(self):
''' Close connection to remote host. '''
pass
def _checkMode(self, name, mode):
pass
def value(mode):
pass
def _getResult(self):
pass
def _sendCommand(self, *command):
pass
@classmethod
def _addMethod(cls, method, name, mode):
pass
def fn(self, *args):
pass
| 11 | 2 | 12 | 2 | 9 | 1 | 2 | 0.14 | 1 | 4 | 0 | 0 | 6 | 5 | 7 | 7 | 111 | 22 | 79 | 25 | 68 | 11 | 61 | 23 | 51 | 6 | 1 | 1 | 18 |
4,494 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._Arg2Obj
|
class _Arg2Obj:
def __init__(self, store):
self.sink = store
def vol(self, uuid):
return None if uuid == 'None' else Store.Volume(uuid, None)
def diff(self, toUUID, fromUUID, estimatedSize='None'):
if estimatedSize == 'None':
return Store.Diff(self.sink, self.vol(toUUID), self.vol(fromUUID))
else:
estimatedSize = int(float(estimatedSize))
return Store.Diff(self.sink, self.vol(toUUID), self.vol(fromUUID), estimatedSize, True)
def bool(self, text):
return text.lower() in ['true', 'yes', 'on', '1', 't', 'y']
|
class _Arg2Obj:
def __init__(self, store):
pass
def vol(self, uuid):
pass
def diff(self, toUUID, fromUUID, estimatedSize='None'):
pass
def bool(self, text):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 0 | 4 | 2 | 0 | 4 | 1 | 4 | 4 | 17 | 4 | 13 | 6 | 8 | 0 | 12 | 6 | 7 | 2 | 0 | 1 | 6 |
4,495 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore.SSHStore
|
class SSHStore(Store.Store):
""" A synchronization source or sink to a btrfs over SSH. """
def __init__(self, host, path, mode, dryrun):
""" Initialize.
:arg host: ssh host.
"""
# For simplicity, only allow absolute paths
# Don't lose a trailing slash -- it's significant
path = "/" + os.path.normpath(path) + ("/" if path.endswith("/") else "")
super(SSHStore, self).__init__(host, path, mode, dryrun)
self.host = host
self._client = _Client(host, 'r' if dryrun else mode, path)
self.isRemote = True
self.toArg = _Obj2Arg()
self.toObj = _Dict2Obj(self)
def __unicode__(self):
""" English description of self. """
return u"ssh://%s%s" % (self.host, self.userPath)
def _open(self):
""" Open connection to remote host. """
self._client._open()
def _close(self):
""" Close connection to remote host. """
self._client._close()
# Abstract methods
def _fillVolumesAndPaths(self, paths):
""" Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
"""
for (volDict, volPaths) in self._client.fillVolumesAndPaths():
vol = Store.Volume(**volDict)
paths[vol] = volPaths
# Abstract methods
def getEdges(self, fromVol):
""" Return the edges available from fromVol. """
return [
self.toObj.diff(diff)
for diff in self._client.getEdges(self.toArg.vol(fromVol))
]
def measureSize(self, diff, chunkSize):
""" Spend some time to get an accurate size. """
(toUUID, fromUUID) = self.toArg.diff(diff)
isInteractive = sys.stderr.isatty()
return self.toObj.diff(self._client.measureSize(
toUUID,
fromUUID,
diff.size,
chunkSize,
isInteractive,
))
def hasEdge(self, diff):
""" True if Store already contains this edge. """
return diff.toVol in self.paths
def send(self, diff):
""" Return Context Manager for a file-like (stream) object to send a diff. """
if Store.skipDryRun(logger, self.dryrun)("send %s", diff):
return None
(diffTo, diffFrom) = self.toArg.diff(diff)
self._client.send(diffTo, diffFrom)
progress = DisplayProgress(diff.size) if self.showProgress is True else None
return _SSHStream(self._client, progress)
def receive(self, diff, paths):
""" Return Context Manager for a file-like (stream) object to store a diff. """
path = self.selectReceivePath(paths)
path = self._relativePath(path)
if Store.skipDryRun(logger, self.dryrun)("receive to %s", path):
return None
(diffTo, diffFrom) = self.toArg.diff(diff)
self._client.receive(path, diffTo, diffFrom)
progress = DisplayProgress(diff.size) if self.showProgress is True else None
return _SSHStream(self._client, progress)
def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path):
return None
self._client.receiveInfo(path)
return _SSHStream(self._client)
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
(toUUID, fromUUID) = self.toArg.diff(diff)
self._client.keep(toUUID, fromUUID)
logger.debug("Kept %s", diff)
def deleteUnused(self):
""" Delete any old snapshots in path, if not kept. """
if self.dryrun:
self._client.listUnused()
else:
self._client.deleteUnused()
def deletePartials(self):
""" Delete any old partial uploads/downloads in path. """
if self.dryrun:
self._client.listPartials()
else:
self._client.deletePartials()
|
class SSHStore(Store.Store):
''' A synchronization source or sink to a btrfs over SSH. '''
def __init__(self, host, path, mode, dryrun):
''' Initialize.
:arg host: ssh host.
'''
pass
def __unicode__(self):
''' English description of self. '''
pass
def _open(self):
''' Open connection to remote host. '''
pass
def _close(self):
''' Close connection to remote host. '''
pass
def _fillVolumesAndPaths(self, paths):
''' Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
'''
pass
def getEdges(self, fromVol):
''' Return the edges available from fromVol. '''
pass
def measureSize(self, diff, chunkSize):
''' Spend some time to get an accurate size. '''
pass
def hasEdge(self, diff):
''' True if Store already contains this edge. '''
pass
def send(self, diff):
''' Return Context Manager for a file-like (stream) object to send a diff. '''
pass
def receive(self, diff, paths):
''' Return Context Manager for a file-like (stream) object to store a diff. '''
pass
def receiveVolumeInfo(self, paths):
''' Return Context Manager for a file-like (stream) object to store volume info. '''
pass
def keep(self, diff):
''' Mark this diff (or volume) to be kept in path. '''
pass
def deleteUnused(self):
''' Delete any old snapshots in path, if not kept. '''
pass
def deletePartials(self):
''' Delete any old partial uploads/downloads in path. '''
pass
| 15 | 15 | 8 | 1 | 5 | 1 | 2 | 0.32 | 1 | 7 | 6 | 0 | 14 | 5 | 14 | 38 | 126 | 30 | 73 | 31 | 58 | 23 | 62 | 31 | 47 | 3 | 2 | 1 | 24 |
4,496 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/S3Store.py
|
buttersink.S3Store._Uploader
|
class _Uploader(io.RawIOBase):
def __init__(self, bucket, keyName, progress=None, bufferSize=None):
self.progress = progress
self.bucket = bucket
self.keyName = keyName.lstrip("/")
self.uploader = None
self.parts = util.DefaultList()
self.chunkCount = None
self.metadata = {}
self.bufferedWriter = None
self.bufferSize = bufferSize
self.exception = None
def __enter__(self):
self.open()
if self.progress:
self.progress.__enter__()
if self.bufferSize:
self.bufferedWriter = io.BufferedWriter(self, buffer_size=self.bufferSize)
return self.bufferedWriter
else:
return self
def open(self):
if self.uploader is not None:
logger.warning(
"Ignoring double open%s",
_displayTraceBack(),
)
return
logger.debug("Opening")
self.chunkCount = 0
self.parts = util.DefaultList()
for upload in self.bucket.list_multipart_uploads():
if upload.key_name != self.keyName:
continue
logger.debug("Upload: %s", upload.__dict__)
for part in upload:
logger.debug(" Part: %s", part.__dict__)
self.parts[part.part_number - 1] = (part.size, part.etag)
if not self.parts:
continue
self.uploader = upload
return
self.uploader = self.bucket.initiate_multipart_upload(
self.keyName,
encrypt_key=isEncrypted,
metadata=self.metadata,
)
assert self.uploader is not None
def __exit__(self, exceptionType, exceptionValue, traceback):
self.exception = exceptionValue
if self.bufferedWriter:
self.bufferedWriter.close()
if self.uploader is not None:
logger.warn("BufferedWriter didn't close raw stream.")
else:
self.close()
if self.progress:
self.progress.__exit__(exceptionType, exceptionValue, traceback)
return False # Don't suppress exception
def skipChunk(self, chunkSize, checkSum, data=None):
part = self.parts[self.chunkCount]
if part is None:
return False
(size, tag) = part
tag = tag.strip('"')
if size != chunkSize:
logger.warning("Unexpected chunk size %d instead of %d", chunkSize, size)
# return False
if tag != checkSum:
logger.warning("Bad check sum %d instead of %d", checkSum, tag)
return False
self.chunkCount += 1
logger.info(
"Skipping already uploaded %s chunk #%d",
humanize(chunkSize),
self.chunkCount,
)
return True
def write(self, bytes):
if len(bytes) == 0:
logger.debug("Ignoring empty upload request.")
return 0
return self.upload(bytes)
def close(self):
if self.uploader is None:
logger.debug(
"Ignoring double close%s",
_displayTraceBack(),
)
return
logger.debug(
"Closing%s",
_displayTraceBack(),
)
if self.exception is None:
self.uploader.complete_upload()
# You cannot change metadata after uploading
# if self.metadata:
# key = self.bucket.get_key(self.keyName)
# key.update_metadata(self.metadata)
else:
# self.uploader.cancel_upload() # Delete (most of) the uploaded chunks.
parts = [part for part in self.uploader]
logger.debug("Uploaded parts: %s", parts)
pass # Leave unfinished upload to resume later
self.uploader = None
def fileno(self):
raise IOError("S3 uploads don't use file numbers.")
def writable(self):
return True
def upload(self, bytes):
if self.chunkCount is None:
raise Exception("Uploading before opening uploader.")
self.chunkCount += 1
size = len(bytes)
fileObject = io.BytesIO(bytes)
if self.progress is None:
self.uploader.upload_part_from_file(
fileObject, self.chunkCount,
)
else:
cb = _BotoProgress(
size,
"Chunk #%d" % (self.chunkCount),
self.progress,
)
with cb:
self.uploader.upload_part_from_file(
fileObject, self.chunkCount, **_BotoProgress.botoArgs(cb)
)
return size
|
class _Uploader(io.RawIOBase):
def __init__(self, bucket, keyName, progress=None, bufferSize=None):
pass
def __enter__(self):
pass
def open(self):
pass
def __exit__(self, exceptionType, exceptionValue, traceback):
pass
def skipChunk(self, chunkSize, checkSum, data=None):
pass
def write(self, bytes):
pass
def close(self):
pass
def fileno(self):
pass
def writable(self):
pass
def upload(self, bytes):
pass
| 11 | 0 | 15 | 2 | 12 | 1 | 3 | 0.08 | 1 | 3 | 2 | 0 | 10 | 10 | 10 | 30 | 162 | 31 | 125 | 29 | 114 | 10 | 96 | 29 | 85 | 6 | 5 | 2 | 28 |
4,497 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/S3Store.py
|
buttersink.S3Store._Downloader
|
class _Downloader(io.RawIOBase):
def __init__(self, key, progress=None):
self.progress = progress
self.key = key
self.mark = 0
def __enter__(self):
if self.progress:
self.progress.__enter__()
return self
def __exit__(self, exceptionType, exceptionValue, traceback):
if self.progress:
self.progress.__exit__(exceptionType, exceptionValue, traceback)
def read(self, n=-1):
if self.mark >= self.key.size or n == 0:
return b''
if n < 0:
headers = None
else:
headers = {"Range": "bytes=%s-%s" % (self.mark, self.mark + n - 1)}
if self.progress is None:
data = self.key.get_contents_as_string(
headers,
)
else:
progress = _BotoProgress(n, "Range", self.progress)
with progress:
data = self.key.get_contents_as_string(
headers, **_BotoProgress.botoArgs(progress)
)
size = len(data)
assert n < 0 or size <= n, (size, data[:10])
self.mark += size
return data
def readable(self):
return True
|
class _Downloader(io.RawIOBase):
def __init__(self, key, progress=None):
pass
def __enter__(self):
pass
def __exit__(self, exceptionType, exceptionValue, traceback):
pass
def read(self, n=-1):
pass
def readable(self):
pass
| 6 | 0 | 8 | 1 | 7 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 5 | 3 | 5 | 25 | 45 | 10 | 35 | 13 | 29 | 0 | 29 | 13 | 23 | 4 | 5 | 2 | 10 |
4,498 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/SSHStore.py
|
buttersink.SSHStore._Obj2Dict
|
class _Obj2Dict:
""" Serialize to dictionary. """
def vol(self, vol):
if vol is None:
return None
return dict(
uuid=vol.uuid,
gen=vol.gen,
size=vol.size,
exclusiveSize=vol.exclusiveSize,
)
def diff(self, diff):
""" Serialize to a dictionary. """
if diff is None:
return None
return dict(
toVol=diff.toUUID,
fromVol=diff.fromUUID,
size=diff.size,
sizeIsEstimated=diff.sizeIsEstimated,
)
|
class _Obj2Dict:
''' Serialize to dictionary. '''
def vol(self, vol):
pass
def diff(self, diff):
''' Serialize to a dictionary. '''
pass
| 3 | 2 | 10 | 0 | 9 | 1 | 2 | 0.11 | 0 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 24 | 3 | 19 | 3 | 16 | 2 | 9 | 3 | 6 | 2 | 0 | 1 | 4 |
4,499 |
AmesCornish/buttersink
|
AmesCornish_buttersink/buttersink/S3Store.py
|
buttersink.S3Store.S3Store
|
class S3Store(Store.Store):
""" An S3 bucket synchronization source or sink. """
def __init__(self, host, path, mode, dryrun):
""" Initialize.
host is the bucket name.
path is an object key prefix to use.
"""
super(S3Store, self).__init__(host, "/" + path, mode, dryrun)
self.bucketName = host
self.keyPattern = re.compile(S3Store.theKeyPattern % ())
# { fromVol: [diff] }
self.diffs = None
self.extraKeys = None
logger.info("Listing %s contents...", self)
try:
# Orginary calling format returns a 301 without specifying a location.
# Subdomain calling format does not require specifying the region.
s3 = boto.s3.connection.S3Connection(
# calling_format=boto.s3.connection.ProtocolIndependentOrdinaryCallingFormat(),
calling_format=boto.s3.connection.SubdomainCallingFormat(),
)
# s3 = boto.connect_s3() # Often fails with 301
# s3 = boto.s3.connect_to_region('us-west-2') # How would we know the region?
except boto.exception.NoAuthHandlerFound:
logger.error("Try putting S3 credentials into ~/.boto")
raise
self.bucket = s3.get_bucket(self.bucketName)
self.isRemote = True
def __unicode__(self):
""" Return text description. """
return u'S3 Bucket "%s"' % (self.bucketName)
def __str__(self):
""" Return text description. """
return unicode(self).encode('utf-8')
def _flushPartialUploads(self, dryrun):
for upload in self.bucket.list_multipart_uploads():
# logger.debug("Upload: %s", upload.__dict__)
# for part in upload:
# logger.debug(" Part: %s", part.__dict__)
if not upload.key_name.startswith(self.userPath.lstrip("/")):
continue
if self._skipDryRun(logger, 'INFO', dryrun)(
"Delete old partial upload: %s (%d parts)",
upload,
len([part for part in upload]),
):
continue
upload.cancel_upload()
def _fillVolumesAndPaths(self, paths):
""" Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
"""
self.diffs = collections.defaultdict((lambda: []))
self.extraKeys = {}
for key in self.bucket.list():
if key.name.startswith(theTrashPrefix):
continue
keyInfo = self._parseKeyName(key.name)
if keyInfo is None:
if key.name[-1:] != '/':
logger.warning("Ignoring '%s' in S3", key.name)
continue
if keyInfo['type'] == 'info':
stream = io.BytesIO()
key.get_contents_to_file(stream)
Store.Volume.readInfo(stream)
continue
if keyInfo['from'] == 'None':
keyInfo['from'] = None
path = self._relativePath("/" + keyInfo['fullpath'])
if path is None:
continue
diff = Store.Diff(self, keyInfo['to'], keyInfo['from'], key.size)
logger.debug("Adding %s in %s", diff, path)
self.diffs[diff.fromVol].append(diff)
paths[diff.toVol].append(path)
self.extraKeys[diff] = path
# logger.debug("Diffs:\n%s", pprint.pformat(self.diffs))
# logger.debug("Vols:\n%s", pprint.pformat(self.vols))
# logger.debug("Extra:\n%s", (self.extraKeys))
def listContents(self):
""" Return list of volumes or diffs in this Store's selected directory. """
items = list(self.extraKeys.items())
items.sort(key=lambda t: t[1])
(count, size) = (0, 0)
for (diff, path) in items:
if path.startswith("/"):
continue
yield str(diff)
count += 1
size += diff.size
yield "TOTAL: %d diffs %s" % (count, humanize(size))
def getEdges(self, fromVol):
""" Return the edges available from fromVol. """
return self.diffs[fromVol]
def hasEdge(self, diff):
""" Test whether edge is in this sink. """
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]]
def measureSize(self, diff, chunkSize):
""" Spend some time to get an accurate size. """
logger.warn("Don't need to measure S3 diffs")
def receive(self, diff, paths):
""" Return Context Manager for a file-like (stream) object to store a diff. """
path = self.selectReceivePath(paths)
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
if self._skipDryRun(logger)("receive %s in %s", keyName, self):
return None
progress = _BotoProgress(diff.size) if self.showProgress is True else None
return _Uploader(self.bucket, keyName, progress)
def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if self._skipDryRun(logger)("receive info in '%s'", path):
return None
return _Uploader(self.bucket, path, bufferSize=theInfoBufferSize)
theKeyPattern = "^(?P<fullpath>.*)/(?P<to>[-a-zA-Z0-9]*)_(?P<from>[-a-zA-Z0-9]*)$"
def _keyName(self, toUUID, fromUUID, path):
return "%s/%s_%s" % (self._fullPath(path).lstrip("/"), toUUID, fromUUID)
def _parseKeyName(self, name):
""" Returns dict with fullpath, to, from. """
if name.endswith(Store.theInfoExtension):
return {'type': 'info'}
match = self.keyPattern.match(name)
if not match:
return None
match = match.groupdict()
match.update(type='diff')
return match
def send(self, diff):
""" Write the diff (toVol from fromVol) to the stream context manager. """
path = self._fullPath(self.extraKeys[diff])
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
key = self.bucket.get_key(keyName)
if self._skipDryRun(logger)("send %s in %s", keyName, self):
return None
progress = _BotoProgress(diff.size) if self.showProgress is True else None
return _Downloader(key, progress)
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
path = self.extraKeys[diff]
if not path.startswith("/"):
logger.debug("Keeping %s", path)
del self.extraKeys[diff]
return
# Copy into self.userPath, if not there already
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
newPath = os.path.join(self.userPath, os.path.basename(path))
newName = self._keyName(diff.toUUID, diff.fromUUID, newPath)
if not self._skipDryRun(logger)("Copy %s to %s", keyName, newName):
self.bucket.copy_key(newName, self.bucket.name, keyName)
def deleteUnused(self):
""" Delete any old snapshots in path, if not kept. """
(count, size) = (0, 0)
for (diff, path) in self.extraKeys.items():
if path.startswith("/"):
continue
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
count += 1
size += diff.size
if self._skipDryRun(logger, 'INFO')("Trash: %s", diff):
continue
try:
self.bucket.copy_key(theTrashPrefix + keyName, self.bucket.name, keyName)
self.bucket.delete_key(keyName)
except boto.exception.S3ResponseError as error:
logger.error("%s: %s", error.code, error.message)
try:
keyName = os.path.dirname(keyName) + Store.theInfoExtension
self.bucket.copy_key(theTrashPrefix + keyName, self.bucket.name, keyName)
self.bucket.delete_key(keyName)
except boto.exception.S3ResponseError as error:
logger.debug("%s: %s", error.code, error.message)
logger.info("Trashed %d diffs (%s)", count, humanize(size))
def deletePartials(self):
""" Delete any old partial uploads/downloads in path. """
self._flushPartialUploads(self.dryrun)
|
class S3Store(Store.Store):
''' An S3 bucket synchronization source or sink. '''
def __init__(self, host, path, mode, dryrun):
''' Initialize.
host is the bucket name.
path is an object key prefix to use.
'''
pass
def __unicode__(self):
''' Return text description. '''
pass
def __str__(self):
''' Return text description. '''
pass
def _flushPartialUploads(self, dryrun):
pass
def _fillVolumesAndPaths(self, paths):
''' Fill in paths.
:arg paths: = { Store.Volume: ["linux path",]}
'''
pass
def listContents(self):
''' Return list of volumes or diffs in this Store's selected directory. '''
pass
def getEdges(self, fromVol):
''' Return the edges available from fromVol. '''
pass
def hasEdge(self, diff):
''' Test whether edge is in this sink. '''
pass
def measureSize(self, diff, chunkSize):
''' Spend some time to get an accurate size. '''
pass
def receive(self, diff, paths):
''' Return Context Manager for a file-like (stream) object to store a diff. '''
pass
def receiveVolumeInfo(self, paths):
''' Return Context Manager for a file-like (stream) object to store volume info. '''
pass
def _keyName(self, toUUID, fromUUID, path):
pass
def _parseKeyName(self, name):
''' Returns dict with fullpath, to, from. '''
pass
def send(self, diff):
''' Write the diff (toVol from fromVol) to the stream context manager. '''
pass
def keep(self, diff):
''' Mark this diff (or volume) to be kept in path. '''
pass
def deleteUnused(self):
''' Delete any old snapshots in path, if not kept. '''
pass
def deletePartials(self):
''' Delete any old partial uploads/downloads in path. '''
pass
| 18 | 16 | 13 | 3 | 8 | 2 | 3 | 0.24 | 1 | 8 | 5 | 0 | 17 | 6 | 17 | 41 | 243 | 66 | 143 | 52 | 125 | 34 | 137 | 51 | 119 | 8 | 2 | 3 | 44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.