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
146,648
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/rulesview.py
elide.rulesview.RuleButton
class RuleButton(ToggleButton, RecycleDataViewBehavior): """A button to select a rule to edit""" rulesview = ObjectProperty() ruleslist = ObjectProperty() rule = ObjectProperty() def on_state(self, *args): """If I'm pressed, unpress all other buttons in the ruleslist""" # This really ought to be done with the selection behavior if self.state == "down": self.rulesview.rule = self.rule for button in self.ruleslist.children[0].children: if button != self: button.state = "normal"
class RuleButton(ToggleButton, RecycleDataViewBehavior): '''A button to select a rule to edit''' def on_state(self, *args): '''If I'm pressed, unpress all other buttons in the ruleslist''' pass
2
2
8
0
6
2
4
0.3
2
0
0
0
1
0
1
1
15
2
10
6
8
3
10
6
8
4
1
3
4
146,649
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/stepper.py
elide.stepper.RuleStepper
class RuleStepper(RecycleView): name = StringProperty() def from_rules_handled_turn(self, rules_handled_turn): data = [ { "widget": "RuleStepperRuleButton", "name": "start", "end_tick": 0, "height": 40, } ] all_rules = [] for rbtyp, rules in rules_handled_turn.items(): for tick, rule in rules.items(): all_rules.append((tick, rbtyp, rule)) all_rules.sort() prev_tick = 0 last_entity = None last_rulebook = None lasttyp = None for tick, rbtyp, (entity, rulebook, rule) in all_rules: if tick == prev_tick: # Rules that aren't triggered are still "handled". Ignore them. continue if lasttyp != rbtyp: data.append({"widget": "RulebookTypeLabel", "name": rbtyp}) lasttyp = rbtyp rulebook_per_entity = rbtyp in {"thing", "place", "portal"} if not rulebook_per_entity: if rulebook != last_rulebook: last_rulebook = rulebook data.append({"widget": "RulebookLabel", "name": rulebook}) if entity != last_entity: last_entity = entity data.append({"widget": "EntityLabel", "name": entity}) if rulebook_per_entity: if rulebook != last_rulebook: rulebook = last_rulebook data.append({"widget": "RulebookLabel", "name": rulebook}) data.append( { "widget": "RuleStepperRuleButton", "name": rule, "start_tick": prev_tick, "end_tick": tick, "height": 40, } ) prev_tick = tick self.data = data
class RuleStepper(RecycleView): def from_rules_handled_turn(self, rules_handled_turn): pass
2
0
47
0
47
1
11
0.02
1
0
0
0
1
1
1
1
50
1
49
14
47
1
34
14
32
11
1
3
11
146,650
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/pawnspot.py
elide.pawnspot.GraphPawnSpot
class GraphPawnSpot(ImageStackProxy, Layout): """The kind of ImageStack that represents a :class:`Thing` or :class:`Place`. """ board = ObjectProperty() engine = ObjectProperty() selected = BooleanProperty(False) linecolor = ListProperty() selected_outline_color = ListProperty([0, 1, 1, 1]) unselected_outline_color = ListProperty([0, 0, 0, 0]) use_boardspace = True def __init__(self, **kwargs): if "proxy" in kwargs: kwargs["name"] = kwargs["proxy"].name super().__init__(**kwargs) self.bind(pos=self._position) def on_touch_move(self, touch): """If I'm being dragged, move to follow the touch.""" if touch.grab_current is not self: return False self.center = touch.pos return True def finalize(self, initial=True): """Call this after you've created all the PawnSpot you need and are ready to add them to the board.""" if getattr(self, "_finalized", False): return if self.proxy is None or not hasattr(self.proxy, "name"): Clock.schedule_once(partial(self.finalize, initial=initial), 0) return if initial: self.name = self.proxy.name if "_image_paths" in self.proxy: try: self.paths = self.proxy["_image_paths"] except Exception as ex: if not ( isinstance(ex.args[0], str) and ex.args[0].startswith("Unable to load image type") ): raise ex self.paths = self.default_image_paths else: self.paths = self.proxy.setdefault( "_image_paths", self.default_image_paths ) zeroes = [0] * len(self.paths) self.offxs = self.proxy.setdefault("_offxs", zeroes) self.offys = self.proxy.setdefault("_offys", zeroes) self.proxy.connect(self._trigger_pull_from_proxy) self.finalize_children(initial=True) self._push_image_paths_binding = self.fbind( "paths", self._trigger_push_image_paths ) self._push_offxs_binding = self.fbind( "offxs", self._trigger_push_offxs ) self._push_offys_binding = self.fbind( "offys", self._trigger_push_offys ) def upd_box_translate(*_): self.box_translate.xy = self.pos def upd_box_points(*_): self.box.points = [ 0, 0, self.width, 0, self.width, self.height, 0, self.height, 0, 0, ] self.boxgrp = boxgrp = InstructionGroup() self.color = Color(*self.linecolor) self.box_translate = Translate(*self.pos) boxgrp.add(PushMatrix()) boxgrp.add(self.box_translate) boxgrp.add(self.color) self.box = Line() upd_box_points() self._upd_box_points_binding = self.fbind("size", upd_box_points) self._upd_box_translate_binding = self.fbind("pos", upd_box_translate) boxgrp.add(self.box) boxgrp.add(Color(1.0, 1.0, 1.0)) boxgrp.add(PopMatrix()) self._finalized = True def unfinalize(self): self.unbind_uid("paths", self._push_image_paths_binding) self.unbind_uid("offxs", self._push_offxs_binding) self.unbind_uid("offys", self._push_offys_binding) self._finalized = False def pull_from_proxy(self, *_): initial = not hasattr(self, "_finalized") self.unfinalize() for key, att in [ ("_image_paths", "paths"), ("_offxs", "offxs"), ("_offys", "offys"), ]: if key in self.proxy and self.proxy[key] != getattr(self, att): setattr(self, att, self.proxy[key]) self.finalize(initial) def _trigger_pull_from_proxy(self, *_, **__): Clock.unschedule(self.pull_from_proxy) Clock.schedule_once(self.pull_from_proxy, 0) @trigger def _trigger_push_image_paths(self, *_): self.proxy["_image_paths"] = list(self.paths) @trigger def _trigger_push_offxs(self, *_): self.proxy["_offxs"] = list(self.offxs) @trigger def _trigger_push_offys(self, *_): self.proxy["_offys"] = list(self.offys) def on_linecolor(self, *_): """If I don't yet have the instructions for drawing the selection box in my canvas, put them there. In any case, set the :class:`Color` instruction to match my current ``linecolor``. """ if hasattr(self, "color"): self.color.rgba = self.linecolor def on_board(self, *_): if not (hasattr(self, "group") and hasattr(self, "boxgrp")): Clock.schedule_once(self.on_board, 0) return self.canvas.add(self.group) self.canvas.add(self.boxgrp) def add_widget(self, wid, index=None, canvas=None): if index is None: for index, child in enumerate(self.children, start=1): if wid.priority < child.priority: index = len(self.children) - index break super().add_widget(wid, index=index, canvas=canvas) self._trigger_layout() def do_layout(self, *_): # First try to lay out my children inside of me, # leaving at least this much space on the sides xpad = self.proxy.get("_xpad", self.width / 4) ypad = self.proxy.get("_ypad", self.height / 4) self.gutter = gutter = self.proxy.get("_gutter", xpad / 2) height = self.height - ypad content_height = 0 too_tall = False width = self.width - xpad content_width = 0 groups = defaultdict(list) for child in self.children: group = child.proxy.get("_group", "") groups[group].append(child) if child.height > height: height = child.height too_tall = True piles = {} # Arrange the groups into piles that will fit in me vertically for group, members in groups.items(): members.sort(key=lambda x: x.width * x.height, reverse=True) high = 0 subgroups = [] subgroup = [] for member in members: high += member.height if high > height: subgroups.append(subgroup) subgroup = [member] high = member.height else: subgroup.append(member) subgroups.append(subgroup) content_height = max( (content_height, sum(wid.height for wid in subgroups[0])) ) content_width += sum( max(wid.width for wid in subgrp) for subgrp in subgroups ) piles[group] = subgroups self.content_width = content_width + gutter * (len(piles) - 1) too_wide = content_width > width # If I'm big enough to fit all this stuff, calculate an offset that will ensure # it's all centered. Otherwise just offset to my top-right so the user can still # reach me underneath all the pawns. if too_wide: offx = self.width else: offx = self.width / 2 - content_width / 2 if too_tall: offy = self.height else: offy = self.height / 2 - content_height / 2 for pile, subgroups in sorted(piles.items()): for subgroup in subgroups: subw = subh = 0 for member in subgroup: rel_y = offy + subh member.rel_pos = (offx, rel_y) x, y = self.pos member.pos = x + offx, y + rel_y subw = max((subw, member.width)) subh += member.height offx += subw offx += gutter def _position(self, *_): x, y = self.pos for child in self.children: offx, offy = getattr(child, "rel_pos", (0, 0)) child.pos = x + offx, y + offy def on_selected(self, *_): if self.selected: self.linecolor = self.selected_outline_color else: self.linecolor = self.unselected_outline_color
class GraphPawnSpot(ImageStackProxy, Layout): '''The kind of ImageStack that represents a :class:`Thing` or :class:`Place`. ''' def __init__(self, **kwargs): pass def on_touch_move(self, touch): '''If I'm being dragged, move to follow the touch.''' pass def finalize(self, initial=True): '''Call this after you've created all the PawnSpot you need and are ready to add them to the board.''' pass def upd_box_translate(*_): pass def upd_box_points(*_): pass def unfinalize(self): pass def pull_from_proxy(self, *_): pass def _trigger_pull_from_proxy(self, *_, **__): pass @trigger def _trigger_push_image_paths(self, *_): pass @trigger def _trigger_push_offxs(self, *_): pass @trigger def _trigger_push_offys(self, *_): pass def on_linecolor(self, *_): '''If I don't yet have the instructions for drawing the selection box in my canvas, put them there. In any case, set the :class:`Color` instruction to match my current ``linecolor``. ''' pass def on_board(self, *_): pass def add_widget(self, wid, index=None, canvas=None): pass def do_layout(self, *_): pass def _position(self, *_): pass def on_selected(self, *_): pass
21
4
13
0
12
1
3
0.08
2
6
0
2
15
18
15
41
234
21
198
76
177
15
160
72
142
11
4
4
44
146,651
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/graph/pawn.py
elide.graph.pawn.Pawn
class Pawn(PawnBehavior, GraphPawnSpot): """A token to represent a :class:`Thing`. :class:`Thing` is the lisien class to represent items that are located in some :class:`Place` or other. Accordingly, :class:`Pawn`'s coordinates are never set directly; they are instead derived from the location of the :class:`Thing` represented. That means a :class:`Pawn` will appear next to the :class:`Spot` representing the :class:`Place` that its :class:`Thing` is in. The exception is if the :class:`Thing` is currently moving from its current :class:`Place` to another one, in which case the :class:`Pawn` will appear some distance along the :class:`Arrow` that represents the :class:`Portal` it's moving through. """ def _get_location_wid(self): return self.board.spot[self.loc_name] def __repr__(self): """Give my ``thing``'s name and its location's name.""" return "<{}-in-{} at {}>".format(self.name, self.loc_name, id(self))
class Pawn(PawnBehavior, GraphPawnSpot): '''A token to represent a :class:`Thing`. :class:`Thing` is the lisien class to represent items that are located in some :class:`Place` or other. Accordingly, :class:`Pawn`'s coordinates are never set directly; they are instead derived from the location of the :class:`Thing` represented. That means a :class:`Pawn` will appear next to the :class:`Spot` representing the :class:`Place` that its :class:`Thing` is in. The exception is if the :class:`Thing` is currently moving from its current :class:`Place` to another one, in which case the :class:`Pawn` will appear some distance along the :class:`Arrow` that represents the :class:`Portal` it's moving through. ''' def _get_location_wid(self): pass def __repr__(self): '''Give my ``thing``'s name and its location's name.''' pass
3
2
3
0
2
1
1
2.8
2
0
0
0
2
0
2
55
23
4
5
3
2
14
5
3
2
1
5
0
2
146,652
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/graph/board.py
elide.graph.board.GraphBoardView
class GraphBoardView(BoardView): adding_portal = BooleanProperty(False) reciprocal_portal = BooleanProperty(True) engine = ObjectProperty() character_name = StringProperty() def on_character_name(self, *args): if ( not self.engine or not self.character_name or self.character_name not in self.engine.character ): Clock.schedule_once(self.on_character_name, 0) return character = self.engine.character[self.character_name] self.board = GraphBoard(character=character)
class GraphBoardView(BoardView): def on_character_name(self, *args): pass
2
0
10
0
10
0
2
0
1
1
1
0
1
1
1
4
16
1
15
8
13
0
11
8
9
2
2
1
2
146,653
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/graph/board.py
elide.graph.board.GraphBoardScatterPlane
class GraphBoardScatterPlane(BoardScatterPlane): selection_candidates = ListProperty([]) selection = ObjectProperty(allownone=True) keep_selection = BooleanProperty(False) board = ObjectProperty() adding_portal = BooleanProperty(False) reciprocal_portal = BooleanProperty() def spot_from_dummy(self, dummy): """Make a real place and its spot from a dummy spot. Create a new :class:`graph.Spot` instance, along with the underlying :class:`lisien.Place` instance, and give it the name, position, and imagery of the provided dummy. """ (x, y) = self.to_local(*dummy.pos_up) x /= self.board.width y /= self.board.height self.board.character.new_place( dummy.name, _x=x, _y=y, _image_paths=list(dummy.paths) ) dummy.num += 1 def pawn_from_dummy(self, dummy): """Make a real thing and its pawn from a dummy pawn. Create a new :class:`graph.Pawn` instance, along with the underlying :class:`lisien.Thing` instance, and give it the name, location, and imagery of the provided dummy. """ candidates = [] dummy_center = self.to_local(*dummy.center) dummy.pos = self.to_local(*dummy.pos) for key in self.board.stack_plane.iter_collided_keys(*dummy_center): if key in self.board.spot: candidates.append(self.board.spot[key]) if not candidates: return whereat = candidates.pop() if candidates: dist = Vector(*whereat.center).distance(dummy_center) while candidates: thereat = candidates.pop() thereto = Vector(*thereat.center).distance(dummy_center) if thereto < dist: whereat, dist = thereat, thereto self.board.character.new_thing( dummy.name, whereat.proxy.name, _image_paths=list(dummy.paths) ) dummy.num += 1 def on_board(self, *args): if hasattr(self, "_oldboard"): self.unbind( adding_portal=self._oldboard.setter("adding_portal"), reciprocal_portal=self._oldboard.setter("reciprocal_portal"), ) self.clear_widgets() self.add_widget(self.board) self.board.adding_portal = self.adding_portal self.board.reciprocal_portal = self.reciprocal_portal self.bind( adding_portal=self.board.setter("adding_portal"), reciprocal_portal=self.board.setter("reciprocal_portal"), ) self._oldboard = self.board
class GraphBoardScatterPlane(BoardScatterPlane): def spot_from_dummy(self, dummy): '''Make a real place and its spot from a dummy spot. Create a new :class:`graph.Spot` instance, along with the underlying :class:`lisien.Place` instance, and give it the name, position, and imagery of the provided dummy. ''' pass def pawn_from_dummy(self, dummy): '''Make a real thing and its pawn from a dummy pawn. Create a new :class:`graph.Pawn` instance, along with the underlying :class:`lisien.Thing` instance, and give it the name, location, and imagery of the provided dummy. ''' pass def on_board(self, *args): pass
4
2
19
1
15
3
3
0.2
1
1
0
0
3
1
3
6
68
7
51
19
47
10
41
19
37
7
2
3
10
146,654
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/util.py
lisien.util.MsgpackExtensionType
class MsgpackExtensionType(Enum): """Type codes for packing special lisien types into msgpack""" tuple = 0x00 frozenset = 0x01 set = 0x02 exception = 0x03 graph = 0x04 character = 0x7F place = 0x7E thing = 0x7D portal = 0x7C final_rule = 0x7B function = 0x7A method = 0x79
class MsgpackExtensionType(Enum): '''Type codes for packing special lisien types into msgpack''' pass
1
1
0
0
0
0
0
0.08
1
0
0
0
0
0
0
49
15
1
13
13
12
1
13
13
12
0
4
0
0
146,655
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/util.py
lisien.util.BadTimeException
class BadTimeException(Exception): """You tried to do something that would make sense at a different game-time But doesn't make sense now """
class BadTimeException(Exception): '''You tried to do something that would make sense at a different game-time But doesn't make sense now ''' pass
1
1
0
0
0
0
0
3
1
0
0
0
0
0
0
10
6
2
1
1
0
3
1
1
0
0
3
0
0
146,656
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_proxy.py
lisien.tests.test_proxy.SetStorageTest
class SetStorageTest(ProxyTest, lisien.allegedb.tests.test_all.SetStorageTest): pass
class SetStorageTest(ProxyTest, lisien.allegedb.tests.test_all.SetStorageTest): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
2
0
2
1
1
0
2
1
1
0
4
0
0
146,657
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_proxy.py
lisien.tests.test_proxy.ProxyGraphTest
class ProxyGraphTest( lisien.allegedb.tests.test_all.AbstractGraphTest, ProxyTest ): pass
class ProxyGraphTest( lisien.allegedb.tests.test_all.AbstractGraphTest, ProxyTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,658
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_proxy.py
lisien.tests.test_proxy.DictStorageTest
class DictStorageTest( ProxyTest, lisien.allegedb.tests.test_all.DictStorageTest ): pass
class DictStorageTest( ProxyTest, lisien.allegedb.tests.test_all.DictStorageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,659
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/graph/spot.py
elide.graph.spot.GraphSpot
class GraphSpot(GraphPawnSpot): """The icon that represents a :class:`Place`. Each :class:`Spot` is located on the Board that represents the :class:`Character` that the underlying :class:`Place` is in. Its coordinates are relative to its :class:`Board`, not necessarily the window the :class:`Board` is in. """ default_image_paths = ["atlas://rltiles/floor.atlas/floor-stone"] default_pos = (0.5, 0.5) def __init__(self, **kwargs): """Deal with triggers and bindings, and arrange to take care of changes in game-time. """ self._pospawn_partials = {} self._pospawn_triggers = {} kwargs["size_hint"] = (None, None) if "place" in kwargs: kwargs["proxy"] = kwargs["place"] del kwargs["place"] super().__init__(**kwargs) def on_board(self, *args): super().on_board(*args) self.board.bind(size=self._upd_pos) def on_pos(self, *args): def upd(orig, dest): bgr = r * bg_scale_selected # change for selectedness pls if (orig, dest) not in port_index: return idx = port_index[orig, dest] inst = instructions[orig, dest] (ox, oy, dx, dy), (x1, y1, endx, endy, x2, y2) = get_points( spot[orig], spot[dest], arrowhead_size ) if ox < dx: bot_left_xs[idx] = ox - bgr top_right_xs[idx] = dx + bgr else: bot_left_xs[idx] = dx - bgr top_right_xs[idx] = ox + bgr if oy < dy: bot_left_ys[idx] = oy - bgr top_right_ys[idx] = dy + bgr else: bot_left_ys[idx] = dy - bgr top_right_ys[idx] = oy + bgr quadverts = get_quad_vertices( ox, oy, dx, dy, x1, y1, endx, endy, x2, y2, bgr, r ) inst["shaft_bg"].points = quadverts["shaft_bg"] colliders[orig, dest] = Collide2DPoly(points=quadverts["shaft_bg"]) inst["left_head_bg"].points = quadverts["left_head_bg"] inst["right_head_bg"].points = quadverts["right_head_bg"] inst["shaft_fg"].points = quadverts["shaft_fg"] inst["left_head_fg"].points = quadverts["left_head_fg"] inst["right_head_fg"].points = quadverts["right_head_fg"] if not self.board: return arrow_plane = self.board.arrow_plane fbo = arrow_plane._fbo arrowhead_size = arrow_plane.arrowhead_size r = arrow_plane.arrow_width // 2 bg_scale_selected = arrow_plane.bg_scale_selected spot = self.board.spot succ = self.board.arrow pred = self.board.pred_arrow name = self.name instructions = arrow_plane._instructions_map colliders = arrow_plane._colliders_map instructions = arrow_plane._instructions_map port_index = arrow_plane._port_index bot_left_xs = arrow_plane._bot_left_corner_xs bot_left_ys = arrow_plane._bot_left_corner_ys top_right_xs = arrow_plane._top_right_corner_xs top_right_ys = arrow_plane._top_right_corner_ys fbo.bind() fbo.clear_buffer() if name in succ: for dest in succ[name]: upd(name, dest) if name in pred: for orig in pred[name]: upd(orig, name) fbo.release() return super().on_pos(*args) def _upd_pos(self, *args): if self.board is None: Clock.schedule_once(self._upd_pos, 0) return self.pos = ( int(self.proxy.get("_x", self.default_pos[0]) * self.board.width), int(self.proxy.get("_y", self.default_pos[1]) * self.board.height), ) def finalize(self, initial=True): if initial: self._upd_pos() super().finalize(initial) def push_pos(self, *args): """Set my current position, expressed as proportions of the graph's width and height, into the ``_x`` and ``_y`` keys of the entity in my ``proxy`` property, such that it will be recorded in the database. """ self.proxy["_x"] = self.x / self.board.width self.proxy["_y"] = self.y / self.board.height _trigger_push_pos = trigger(push_pos) def on_touch_up(self, touch): if touch.grab_current is not self: return False self.center = touch.pos self._trigger_push_pos() touch.ungrab(self) self._trigger_push_pos() return True def __repr__(self): """Give my name and position.""" return "<{}@({},{}) at {}>".format(self.name, self.x, self.y, id(self))
class GraphSpot(GraphPawnSpot): '''The icon that represents a :class:`Place`. Each :class:`Spot` is located on the Board that represents the :class:`Character` that the underlying :class:`Place` is in. Its coordinates are relative to its :class:`Board`, not necessarily the window the :class:`Board` is in. ''' def __init__(self, **kwargs): '''Deal with triggers and bindings, and arrange to take care of changes in game-time. ''' pass def on_board(self, *args): pass def on_pos(self, *args): pass def upd(orig, dest): pass def _upd_pos(self, *args): pass def finalize(self, initial=True): pass def push_pos(self, *args): '''Set my current position, expressed as proportions of the graph's width and height, into the ``_x`` and ``_y`` keys of the entity in my ``proxy`` property, such that it will be recorded in the database. ''' pass def on_touch_up(self, touch): pass def __repr__(self): '''Give my name and position.''' pass
10
4
16
0
14
1
2
0.16
1
2
0
0
8
4
8
49
131
15
101
40
91
16
92
40
82
6
5
2
21
146,660
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_character.py
lisien.tests.test_character.CharacterSetStorageTest
class CharacterSetStorageTest( CharacterTest, lisien.allegedb.tests.test_all.SetStorageTest ): pass
class CharacterSetStorageTest( CharacterTest, lisien.allegedb.tests.test_all.SetStorageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,661
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_character.py
lisien.tests.test_character.CharacterDictStorageTest
class CharacterDictStorageTest( CharacterTest, lisien.allegedb.tests.test_all.DictStorageTest ): pass
class CharacterDictStorageTest( CharacterTest, lisien.allegedb.tests.test_all.DictStorageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,662
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_character.py
lisien.tests.test_character.CharacterBranchLineageTest
class CharacterBranchLineageTest( CharacterTest, lisien.allegedb.tests.test_all.AbstractBranchLineageTest ): pass
class CharacterBranchLineageTest( CharacterTest, lisien.allegedb.tests.test_all.AbstractBranchLineageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
77
4
0
4
3
1
0
2
1
1
0
4
0
0
146,663
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/query.py
lisien.query.UnionQuery
class UnionQuery(CompoundQuery): oper = operator.or_
class UnionQuery(CompoundQuery): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
146,664
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/query.py
lisien.query.NeQuery
class NeQuery(ComparisonQuery): oper = ne
class NeQuery(ComparisonQuery): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
2
1
0
2
2
1
0
3
0
0
146,665
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/query.py
lisien.query.MinusQuery
class MinusQuery(CompoundQuery): oper = operator.sub
class MinusQuery(CompoundQuery): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
2
1
0
2
2
1
0
3
0
0
146,666
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/query.py
lisien.query.LtQuery
class LtQuery(ComparisonQuery): oper = lt
class LtQuery(ComparisonQuery): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
2
1
0
2
2
1
0
3
0
0
146,667
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/query.py
lisien.query.LeQuery
class LeQuery(ComparisonQuery): oper = le
class LeQuery(ComparisonQuery): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
15
2
0
2
2
1
0
2
2
1
0
3
0
0
146,668
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/rulesview.py
elide.rulesview.CharacterRulesScreen
class CharacterRulesScreen(Screen): """Screen with TabbedPanel for all the character-rulebooks""" character = ObjectProperty() toggle = ObjectProperty() def _get_rulebook(self, rb): return { "character": self.character.rulebook, "unit": self.character.unit.rulebook, "character_thing": self.character.thing.rulebook, "character_place": self.character.place.rulebook, "character_portal": self.character.portal.rulebook, }[rb] def finalize(self, *args): assert not hasattr(self, "_finalized") if not (self.toggle and self.character): Clock.schedule_once(self.finalize, 0) return self._tabs = TabbedPanel(do_default_tab=False) for rb, txt in ( ("character", "character"), ("unit", "unit"), ("character_thing", "thing"), ("character_place", "place"), ("character_portal", "portal"), ): tab = TabbedPanelItem(text=txt) setattr(self, "_{}_tab".format(rb), tab) box = RulesBox( rulebook=self._get_rulebook(rb), entity=self.character, toggle=self.toggle, ) setattr(self, "_{}_box".format(rb), box) tab.add_widget(box) self._tabs.add_widget(tab) self.add_widget(self._tabs) self._finalized = True def on_character(self, *_): if not hasattr(self, "_finalized"): self.finalize() return for rb in ( "character", "unit", "character_thing", "character_place", "character_portal", ): tab = getattr(self, "_{}_tab".format(rb)) tab.content.entity = self.character tab.content.rulebook = self._get_rulebook(rb)
class CharacterRulesScreen(Screen): '''Screen with TabbedPanel for all the character-rulebooks''' def _get_rulebook(self, rb): pass def finalize(self, *args): pass def on_character(self, *_): pass
4
1
16
0
16
0
2
0.02
1
1
1
0
3
2
3
3
55
4
50
13
46
1
28
13
24
3
1
1
7
146,669
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_character.py
lisien.tests.test_character.CharacterListStorageTest
class CharacterListStorageTest( CharacterTest, lisien.allegedb.tests.test_all.ListStorageTest ): pass
class CharacterListStorageTest( CharacterTest, lisien.allegedb.tests.test_all.ListStorageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,670
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/grid/board.py
elide.grid.board.GridBoard
class GridBoard(Widget): selection = ObjectProperty() selection_candidates = ListProperty() character = ObjectProperty() tile_width = NumericProperty(32) tile_height = NumericProperty(32) tile_size = ReferenceListProperty(tile_width, tile_height) pawn_cls = GridPawn spot_cls = GridSpot def __init__(self, **kwargs): self.pawn = {} self.spot = {} self.contained = defaultdict(set) super().__init__(**kwargs) def update(self): make_spot = self.make_spot make_pawn = self.make_pawn self.spot_plane.data = list( map(make_spot, self.character.place.values()) ) self.pawn_plane.data = list( map(make_pawn, self.character.thing.values()) ) self.spot_plane.redraw() self.pawn_plane.redraw() def add_spot(self, placen, *args): if placen not in self.character.place: raise KeyError(f"No such place for spot: {placen}") if placen in self.spot: raise KeyError("Already have a Spot for this Place") spt = self.make_spot(self.character.place[placen]) self.spot_plane.add_datum(spt) self.spot[placen] = self.spot_cls(board=self, proxy=spt["proxy"]) def make_spot(self, place): placen = place["name"] if not isinstance(placen, tuple) or len(placen) != 2: raise TypeError( "Can only make spot from places with tuple names of length 2", placen, ) if ( not isinstance(placen, tuple) or len(placen) != 2 or not isinstance(placen[0], int) or not isinstance(placen[1], int) ): raise TypeError( "GridBoard can only display places named with pairs of ints" ) if "_image_paths" in place: textures = list(place["_image_paths"]) else: textures = list(self.spot_cls.default_image_paths) r = { "name": placen, "x": int(placen[0] * self.tile_width), "y": int(placen[1] * self.tile_height), "width": int(self.tile_width), "height": int(self.tile_height), "textures": textures, "proxy": place, } return r def make_pawn(self, thing) -> dict: location = self.spot[thing["location"]] r = { "name": thing["name"], "x": int(location.x), "y": int(location.y), "width": int(self.tile_width), "height": int(self.tile_height), "location": location, "textures": list( thing.get("_image_paths", self.pawn_cls.default_image_paths) ), "proxy": thing, } return r def add_pawn(self, thingn, *args): if thingn not in self.character.thing: raise KeyError(f"No such thing: {thingn}") if thingn in self.pawn: raise KeyError(f"Already have a pawn for {thingn}") thing = self.character.thing[thingn] if thing["location"] not in self.spot: # The location is not in the grid. That's fine. return pwn = self.make_pawn(thing) self.pawn[thingn] = self.pawn_cls(board=self, proxy=pwn["proxy"]) location = pwn["location"] self.contained[location].add(thingn) self.pawn_plane.add_datum(pwn) def _trigger_add_pawn(self, thingn): part = partial(self.add_pawn, thingn) Clock.unschedule(part) Clock.schedule_once(part, 0) def on_parent(self, *args): if self.character is None: Clock.schedule_once(self.on_parent, 0) return if self.character.engine.closed: return Logger.debug("GridBoard: on_parent start") start_ts = monotonic() if not hasattr(self, "pawn_plane"): self.pawn_plane = TextureStackPlane(pos=self.pos, size=self.size) self.spot_plane = TextureStackPlane(pos=self.pos, size=self.size) self.bind( pos=self.pawn_plane.setter("pos"), size=self.pawn_plane.setter("size"), ) self.bind( pos=self.spot_plane.setter("pos"), size=self.spot_plane.setter("size"), ) self.add_widget(self.spot_plane) self.add_widget(self.pawn_plane) spot_data = list( map( self.make_spot, filter( lambda spot: isinstance(spot["name"], tuple) and len(spot["name"]) == 2, self.character.place.values(), ), ) ) if not spot_data: if hasattr(self.spot_plane, "_redraw_bind_uid"): self.spot_plane.unbind_uid( "data", self.spot_plane._redraw_bind_uid ) del self.spot_plane._redraw_bind_uid if hasattr(self.pawn_plane, "_redraw_bind_uid"): self.pawn_plane.unbind_uid( "data", self.pawn_plane._redraw_bind_uid ) del self.pawn_plane._redraw_bind_uid self.spot_plane.data = self.pawn_plane.data = [] self.spot_plane.redraw() self.pawn_plane.redraw() self.spot_plane._redraw_bind_uid = self.spot_plane.fbind( "data", self.spot_plane._trigger_redraw ) self.pawn_plane._redraw_bind_uid = self.pawn_plane.fbind( "data", self.pawn_plane._trigger_redraw ) self.character.thing.connect(self.update_from_thing) self.character.place.connect(self.update_from_place) return for spt in spot_data: self.spot[spt["name"]] = self.spot_cls( board=self, proxy=spt["proxy"] ) self.spot_plane.unbind_uid("data", self.spot_plane._redraw_bind_uid) self.spot_plane.data = spot_data self.spot_plane.redraw() self.spot_plane._redraw_bind_uid = self.spot_plane.fbind( "data", self.spot_plane._trigger_redraw ) wide = max(datum["x"] for datum in spot_data) + self.tile_width high = max(datum["y"] for datum in spot_data) + self.tile_width self.size = self.spot_plane.size = self.pawn_plane.size = wide, high pawn_data = list( map( self.make_pawn, filter( lambda thing: thing["location"] in self.spot, self.character.thing.values(), ), ) ) for pwn in pawn_data: self.pawn[pwn["name"]] = self.pawn_cls( board=self, proxy=pwn["proxy"] ) self.pawn_plane.data = pawn_data self.character.thing.connect(self.update_from_thing) self.character.place.connect(self.update_from_place) Logger.debug( f"GridBoard: on_parent end, took {monotonic() - start_ts:,.2f}" f" seconds" ) def rm_spot(self, name): spot = self.spot.pop(name) if spot in self.selection_candidates: self.selection_candidates.remove(spot) for thing in spot.proxy.contents(): self.rm_pawn(thing.name) self.spot_plane.remove(name) def rm_pawn(self, name): pwn = self.pawn.pop(name) if pwn in self.selection_candidates: self.selection_candidates.remove(pwn) self.pawn_plane.remove(name) def update_from_thing(self, thing, key, value): if thing and not (key is None and not value): if thing.name not in self.pawn: self.add_pawn(thing.name) elif key == "location": if value in self.spot: loc = self.spot[value] pwn = self.pawn[thing.name] pwn.pos = loc.pos elif thing.name in self.pawn: self.rm_pawn(thing.name) elif key == "_image_paths": self.pawn[thing.name].paths = value else: if thing.name in self.pawn: self.rm_pawn(thing.name) def update_from_place(self, place, key, value): if place and not (key is None and not value): if key == "_image_paths": self.spot[place.name].paths = value else: if place.name in self.spot: self.rm_spot(place.name) def on_touch_down(self, touch): self.selection_candidates.extend( chain( map( self.pawn.get, self.pawn_plane.iter_collided_keys(*touch.pos), ), map( self.spot.get, self.spot_plane.iter_collided_keys(*touch.pos), ), ) ) return super().on_touch_down(touch) def on_touch_up(self, touch): touched = { candidate for candidate in self.selection_candidates if candidate.collide_point(*touch.pos) } if not touched: self.selection_candidates = [] return super().on_touch_up(touch) if len(touched) == 1: self.selection = touched.pop() self.selection_candidates = [] return super().on_touch_up(touch) pawns_touched = { node for node in touched if isinstance(node, self.pawn_cls) } if len(pawns_touched) == 1: self.selection = pawns_touched.pop() self.selection_candidates = [] return super().on_touch_up(touch) elif pawns_touched: # TODO: Repeatedly touching a spot with multiple pawns on it # should cycle through the pawns, and then finally the spot. self.selection = pawns_touched.pop() self.selection_candidates = [] return super().on_touch_up(touch) spots_touched = touched - pawns_touched if len(spots_touched) == 1: self.selection = spots_touched.pop() self.selection_candidates = [] return super().on_touch_up(touch) assert not spots_touched, ( "How do you have overlapping spots on a GridBoard??" ) self.selection_candidates = [] return super().on_touch_up(touch)
class GridBoard(Widget): def __init__(self, **kwargs): pass def update(self): pass def add_spot(self, placen, *args): pass def make_spot(self, place): pass def make_pawn(self, thing) -> dict: pass def add_pawn(self, thingn, *args): pass def _trigger_add_pawn(self, thingn): pass def on_parent(self, *args): pass def rm_spot(self, name): pass def rm_pawn(self, name): pass def update_from_thing(self, thing, key, value): pass def update_from_place(self, place, key, value): pass def on_touch_down(self, touch): pass def on_touch_up(self, touch): pass
15
0
17
0
17
0
3
0.01
1
13
1
1
14
7
14
14
262
14
245
56
230
3
154
56
139
8
1
3
46
146,671
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/tests/test_proxy.py
lisien.tests.test_proxy.ListStorageTest
class ListStorageTest( ProxyTest, lisien.allegedb.tests.test_all.ListStorageTest ): pass
class ListStorageTest( ProxyTest, lisien.allegedb.tests.test_all.ListStorageTest ): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
76
4
0
4
3
1
0
2
1
1
0
4
0
0
146,672
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/pallet.py
elide.pallet.SwatchButton
class SwatchButton(ToggleButton): """Toggle button containing a texture and its name, which, when toggled, will report the fact to the :class:`Pallet` it's in. """ tex = ObjectProperty() """Texture to display here""" def on_state(self, *_): if self.state == "down": assert self not in self.parent.selection if self.parent.selection_mode == "single": for wid in self.parent.selection: if wid is not self: wid.state = "normal" self.parent.selection = [self] else: self.parent.selection.append(self) else: if self in self.parent.selection: self.parent.selection.remove(self)
class SwatchButton(ToggleButton): '''Toggle button containing a texture and its name, which, when toggled, will report the fact to the :class:`Pallet` it's in. ''' def on_state(self, *_): pass
2
1
13
0
13
0
6
0.27
1
0
0
0
1
0
1
1
22
3
15
4
13
4
13
4
11
6
1
4
6
146,673
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/menu.py
elide.menu.MenuIntInput
class MenuIntInput(MenuTextInput): """Special text input for setting the turn or tick""" def insert_text(self, s, from_undo=False): """Natural numbers only.""" return super().insert_text( "".join(c for c in s if c in "0123456789"), from_undo )
class MenuIntInput(MenuTextInput): '''Special text input for setting the turn or tick''' def insert_text(self, s, from_undo=False): '''Natural numbers only.''' pass
2
2
5
0
4
1
1
0.4
1
1
0
0
1
0
1
5
8
1
5
2
3
2
3
2
1
1
2
0
1
146,674
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/menu.py
elide.menu.MenuTextInput
class MenuTextInput(TextInput): """Special text input for setting the branch""" set_value = ObjectProperty() def __init__(self, **kwargs): """Disable multiline, and bind ``on_text_validate`` to ``on_enter``""" kwargs["multiline"] = False super().__init__(**kwargs) self.bind(on_text_validate=self.on_enter) def on_enter(self, *_): """Call the setter and blank myself out so that my hint text shows up. It will be the same you just entered if everything's working. """ if self.text == "": return self.set_value(Clock.get_time(), self.text) self.text = "" self.focus = False def on_focus(self, *args): """If I've lost focus, treat it as if the user hit Enter.""" if not self.focus: self.on_enter(*args) def on_text_validate(self, *_): """Equivalent to hitting Enter.""" self.on_enter()
class MenuTextInput(TextInput): '''Special text input for setting the branch''' def __init__(self, **kwargs): '''Disable multiline, and bind ``on_text_validate`` to ``on_enter``''' pass def on_enter(self, *_): '''Call the setter and blank myself out so that my hint text shows up. It will be the same you just entered if everything's working. ''' pass def on_focus(self, *args): '''If I've lost focus, treat it as if the user hit Enter.''' pass def on_text_validate(self, *_): '''Equivalent to hitting Enter.''' pass
5
5
6
0
4
2
2
0.47
1
1
0
1
4
2
4
4
31
6
17
8
12
8
17
8
12
2
1
1
6
146,675
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/menu.py
elide.menu.WorldStartConfigurator
class WorldStartConfigurator(BoxLayout): """Give options for how to initialize the world state""" grid_config = ObjectProperty() generator_type = OptionProperty(None, options=["grid"], allownone=True) dismiss = ObjectProperty() toggle = ObjectProperty() init_board = ObjectProperty() generator_dropdown = ObjectProperty() def on_generator_dropdown(self, *_): def select_txt(btn): self.generator_dropdown.select(btn.text) for opt in ["None", "Grid"]: self.generator_dropdown.add_widget( GeneratorButton(text=opt, on_release=select_txt) ) self.generator_dropdown.bind(on_select=self.select_generator_type) def select_generator_type(self, instance, value): self.ids.drop.text = value if value == "None": self.ids.controls.clear_widgets() self.generator_type = None elif value == "Grid": self.ids.controls.clear_widgets() self.ids.controls.add_widget(self.grid_config) self.grid_config.size = self.ids.controls.size self.grid_config.pos = self.ids.controls.pos self.generator_type = "grid" def start(self, *_): app = App.get_running_app() starter = app.start_subprocess init_board = app.init_board if self.generator_type == "grid": if self.grid_config.validate(): engine = starter() self.grid_config.generate(engine) init_board() self.toggle() self.dismiss() else: # TODO show error return elif not hasattr(self, "_starting"): self._starting = True starter() init_board() self.toggle() self.dismiss()
class WorldStartConfigurator(BoxLayout): '''Give options for how to initialize the world state''' def on_generator_dropdown(self, *_): pass def select_txt(btn): pass def select_generator_type(self, instance, value): pass def start(self, *_): pass
5
1
11
0
10
0
3
0.04
1
1
1
0
3
1
3
3
52
5
45
17
40
2
40
17
35
4
1
2
10
146,676
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/menu.py
elide.menu.DirPicker
class DirPicker(Screen): toggle = ObjectProperty() @triggered() def open(self, path, *_): app = App.get_running_app() if "world" not in os.listdir(path): # TODO show a configurator, accept cancellation, extract init params if not hasattr(self, "config_popover"): self.config_popover = ModalView() self.configurator = WorldStartConfigurator( grid_config=GridGeneratorDialog(), dismiss=self.config_popover.dismiss, toggle=self.toggle, generator_dropdown=DropDown(), ) self.config_popover.add_widget(self.configurator) self.config_popover.open() return app.start_subprocess(path) app.init_board() self.toggle()
class DirPicker(Screen): @triggered() def open(self, path, *_): pass
3
0
18
0
17
1
3
0.05
1
2
2
0
1
2
1
1
22
1
20
7
17
1
14
6
12
3
1
2
3
146,677
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/pallet.py
elide.pallet.Pallet
class Pallet(StackLayout): """Many :class:`SwatchButton`, gathered from an :class:`kivy.atlas.Atlas`.""" atlas = ObjectProperty() """:class:`kivy.atlas.Atlas` object I'll make :class:`SwatchButton` from.""" filename = StringProperty() """Path to an atlas; will construct :class:`kivy.atlas.Atlas` when set""" swatches = DictProperty({}) """:class:`SwatchButton` widgets here, keyed by name of their graphic""" swatch_width = NumericProperty(100) """Width of each and every :class:`SwatchButton` here""" swatch_height = NumericProperty(75) """Height of each and every :class:`SwatchButton` here""" swatch_size = ReferenceListProperty(swatch_width, swatch_height) """Size of each and every :class:`SwatchButton` here""" selection = ListProperty([]) """List of :class:`SwatchButton`s that are selected""" selection_mode = OptionProperty("single", options=["single", "multiple"]) """Whether to allow only a 'single' selected :class:`SwatchButton` (default), or 'multiple'""" def __init__(self, **kwargs): self._trigger_upd_textures = Clock.create_trigger(self.upd_textures) super().__init__(**kwargs) def on_selection(self, *_): Logger.debug( "Pallet: {} got selection {}".format(self.filename, self.selection) ) def on_filename(self, *_): if not self.filename: return resource = resource_find(self.filename) if not resource: raise ValueError("Couldn't find atlas: {}".format(self.filename)) self.atlas = Atlas(resource) def on_atlas(self, *_): if self.atlas is None: return self.upd_textures() self.atlas.bind(textures=self._trigger_upd_textures) def upd_textures(self, *_): """Create one :class:`SwatchButton` for each texture""" if self.canvas is None: Clock.schedule_once(self.upd_textures, 0) return swatches = self.swatches atlas_textures = self.atlas.textures remove_widget = self.remove_widget add_widget = self.add_widget swatch_size = self.swatch_size for name, swatch in list(swatches.items()): if name not in atlas_textures: remove_widget(swatch) del swatches[name] for name, tex in atlas_textures.items(): if name in swatches and swatches[name] != tex: remove_widget(swatches[name]) if name not in swatches or swatches[name] != tex: swatches[name] = SwatchButton( text=name, tex=tex, size_hint=(None, None), size=swatch_size, ) add_widget(swatches[name])
class Pallet(StackLayout): '''Many :class:`SwatchButton`, gathered from an :class:`kivy.atlas.Atlas`.''' def __init__(self, **kwargs): pass def on_selection(self, *_): pass def on_filename(self, *_): pass def on_atlas(self, *_): pass def upd_textures(self, *_): '''Create one :class:`SwatchButton` for each texture''' pass
6
2
9
0
9
0
3
0.19
1
4
1
0
5
1
5
5
68
6
52
23
46
10
45
23
39
7
1
2
14
146,678
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/grid/board.py
elide.grid.board.GridPawn
class GridPawn(Stack): default_image_paths = ["atlas://rltiles/base.atlas/unseen"] @property def _stack_plane(self): return self.board.pawn_plane
class GridPawn(Stack): @property def _stack_plane(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
31
6
1
5
4
2
0
4
3
2
1
1
0
1
146,679
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/kivygarden/texturestack/__init__.py
elide.kivygarden.texturestack.TextureStackBatchWidget
class TextureStackBatchWidget(Widget): """Widget for efficiently drawing many TextureStacks Only add TextureStack or ImageStack widgets to this. Avoid adding any that are to be changed frequently. """ critical_props = ["texs", "offxs", "offys", "pos"] """Properties that, when changed on my children, force a redraw.""" def __init__(self, **kwargs): self._trigger_redraw = Clock.create_trigger(self.redraw) self._trigger_rebind_children = Clock.create_trigger( self.rebind_children ) super(TextureStackBatchWidget, self).__init__(**kwargs) def on_parent(self, *args): if not self.canvas: Clock.schedule_once(self.on_parent, 0) return if not hasattr(self, "_fbo"): with self.canvas: self._fbo = Fbo(size=self.size) self._fbo.add_reload_observer(self.redraw) self._translate = Translate(x=self.x, y=self.y) self._rectangle = Rectangle( texture=self._fbo.texture, size=self.size ) self.rebind_children() def rebind_children(self, *args): child_by_uid = {} binds = {prop: self._trigger_redraw for prop in self.critical_props} for child in self.children: child_by_uid[child.uid] = child child.bind(**binds) if hasattr(self, "_old_children"): old_children = self._old_children for uid in set(old_children).difference(child_by_uid): old_children[uid].unbind(**binds) self.redraw() self._old_children = child_by_uid def redraw(self, *args): fbo = self._fbo fbo.bind() fbo.clear() fbo.clear_buffer() fbo.release() for child in self.children: assert child.canvas not in fbo.children fbo.add(child.canvas) def on_pos(self, *args): if not hasattr(self, "_translate"): return self._translate.x, self._translate.y = self.pos def on_size(self, *args): if not hasattr(self, "_rectangle"): return self._rectangle.size = self._fbo.size = self.size self.redraw() def add_widget(self, widget, index=0, canvas=None): if not isinstance(widget, TextureStack): raise TypeError("TextureStackBatch is only for TextureStack") if index == 0 or len(self.children) == 0: self.children.insert(0, widget) else: children = self.children if index >= len(children): index = len(children) children.insert(index, widget) widget.parent = self if hasattr(self, "_fbo"): self.rebind_children() def remove_widget(self, widget): if widget not in self.children: return self.children.remove(widget) widget.parent = None if hasattr(self, "_fbo"): self.rebind_children()
class TextureStackBatchWidget(Widget): '''Widget for efficiently drawing many TextureStacks Only add TextureStack or ImageStack widgets to this. Avoid adding any that are to be changed frequently. ''' def __init__(self, **kwargs): pass def on_parent(self, *args): pass def rebind_children(self, *args): pass def redraw(self, *args): pass def on_pos(self, *args): pass def on_size(self, *args): pass def add_widget(self, widget, index=0, canvas=None): pass def remove_widget(self, widget): pass
9
1
9
0
9
0
3
0.07
1
4
1
0
8
7
8
8
88
12
71
24
62
5
66
24
57
5
1
2
22
146,680
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/kivygarden/texturestack/__init__.py
elide.kivygarden.texturestack.TextureStack
class TextureStack(Widget): """Several textures superimposed on one another, and possibly offset by some amount. In 2D games where characters can wear different clothes or hold different equipment, their graphics are often composed of several graphics layered on one another. This widget simplifies the management of such compositions. """ texs = ListProperty() """Texture objects""" offxs = ListProperty() """x-offsets. The texture at the same index will be moved to the right by the number of pixels in this list. """ offys = ListProperty() """y-offsets. The texture at the same index will be moved upward by the number of pixels in this list. """ group = ObjectProperty() """My ``InstructionGroup``, suitable for addition to whatever ``canvas``.""" def _get_offsets(self): return zip(self.offxs, self.offys) def _set_offsets(self, offs): offxs = [] offys = [] for x, y in offs: offxs.append(x) offys.append(y) self.offxs, self.offys = offxs, offys offsets = AliasProperty( _get_offsets, _set_offsets, bind=("offxs", "offys") ) """List of (x, y) tuples by which to offset the corresponding texture.""" _texture_rectangles = DictProperty({}) """Private. Rectangle instructions for each of the textures, keyed by the texture. """ def __init__(self, **kwargs): """Make triggers and bind.""" kwargs["size_hint"] = (None, None) self.translate = Translate(0, 0) self.group = InstructionGroup() super().__init__(**kwargs) self.bind(offxs=self.on_pos, offys=self.on_pos) def on_texs(self, *args): """Make rectangles for each of the textures and add them to the canvas.""" if not self.canvas or not self.texs: Clock.schedule_once(self.on_texs, 0) return texlen = len(self.texs) # Ensure each property is the same length as my texs, padding # with 0 as needed for prop in ("offxs", "offys"): proplen = len(getattr(self, prop)) if proplen > texlen: setattr(self, prop, getattr(self, prop)[: proplen - texlen]) if texlen > proplen: propval = list(getattr(self, prop)) propval += [0] * (texlen - proplen) setattr(self, prop, propval) self.canvas.remove(self.group) self.group = InstructionGroup() self._texture_rectangles = {} w = h = 0 (x, y) = self.pos self.translate.x = x self.translate.y = y self.group.add(PushMatrix()) self.group.add(self.translate) for tex, offx, offy in zip(self.texs, self.offxs, self.offys): rect = Rectangle(pos=(offx, offy), size=tex.size, texture=tex) self._texture_rectangles[tex] = rect self.group.add(rect) tw = tex.width + offx th = tex.height + offy if tw > w: w = tw if th > h: h = th self.size = (w, h) self.group.add(PopMatrix()) self.canvas.add(self.group) self.canvas.ask_update() def on_pos(self, *args): """Translate all the rectangles within this widget to reflect the widget's position.""" (x, y) = self.pos self.translate.x = x self.translate.y = y def clear(self): """Clear my rectangles and ``texs``.""" self.group.clear() self._texture_rectangles = {} self.texs = [] self.size = [1, 1] def insert(self, i, tex): """Insert the texture into my ``texs``, waiting for the creation of the canvas if necessary. """ if not self.canvas: Clock.schedule_once(lambda dt: self.insert(i, tex), 0) return self.texs.insert(i, tex) def append(self, tex): """``self.insert(len(self.texs), tex)``""" self.insert(len(self.texs), tex) def __delitem__(self, i): """Remove a texture and its rectangle""" tex = self.texs[i] try: rect = self._texture_rectangles[tex] self.canvas.remove(rect) del self._texture_rectangles[tex] except KeyError: pass del self.texs[i] def __setitem__(self, i, v): """First delete at ``i``, then insert there""" if len(self.texs) > 0: self._no_upd_texs = True self.__delitem__(i) self._no_upd_texs = False self.insert(i, v) def pop(self, i=-1): """Delete the texture at ``i``, and return it.""" return self.texs.pop(i)
class TextureStack(Widget): '''Several textures superimposed on one another, and possibly offset by some amount. In 2D games where characters can wear different clothes or hold different equipment, their graphics are often composed of several graphics layered on one another. This widget simplifies the management of such compositions. ''' def _get_offsets(self): pass def _set_offsets(self, offs): pass def __init__(self, **kwargs): '''Make triggers and bind.''' pass def on_texs(self, *args): '''Make rectangles for each of the textures and add them to the canvas.''' pass def on_pos(self, *args): '''Translate all the rectangles within this widget to reflect the widget's position.''' pass def clear(self): '''Clear my rectangles and ``texs``.''' pass def insert(self, i, tex): '''Insert the texture into my ``texs``, waiting for the creation of the canvas if necessary. ''' pass def append(self, tex): '''``self.insert(len(self.texs), tex)``''' pass def __delitem__(self, i): '''Remove a texture and its rectangle''' pass def __setitem__(self, i, v): '''First delete at ``i``, then insert there''' pass def pop(self, i=-1): '''Delete the texture at ``i``, and return it.''' pass
12
10
9
0
8
1
2
0.35
1
4
0
1
11
3
11
11
146
20
93
37
81
33
91
37
79
8
1
2
22
146,681
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/kivygarden/texturestack/__init__.py
elide.kivygarden.texturestack.ImageStack
class ImageStack(TextureStack): """Instead of supplying textures themselves, supply paths to where the textures may be loaded from. """ paths = ListProperty() """List of paths to images you want stacked.""" pathtexs = DictProperty() """Private. Dictionary mapping image paths to textures of the images.""" pathimgs = DictProperty() """Dictionary mapping image paths to ``kivy.core.Image`` objects.""" def on_paths(self, *args): """Make textures from the images in ``paths``, and assign them at the same index in my ``texs`` as in my ``paths``. """ for i, path in enumerate(self.paths): if path in self.pathtexs: if ( self.pathtexs[path] in self.texs and self.texs.index(self.pathtexs[path]) == i ): continue else: try: self.pathimgs[path] = img = Image.load( resource_find(path), keep_data=True ) except Exception: self.pathimgs[path] = img = Image.load( resource_find("atlas://rltiles/misc/floppy"), keep_data=True, ) self.pathtexs[path] = img.texture if i == len(self.texs): self.texs.append(self.pathtexs[path]) else: self.texs[i] = self.pathtexs[path] def clear(self): """Clear paths, textures, rectangles""" self.paths = [] super().clear() def insert(self, i, v): """Insert a string to my paths""" if not isinstance(v, str): raise TypeError("Paths only") self.paths.insert(i, v) def __delitem__(self, i): """Delete texture, rectangle, path""" super().__delitem__(i) del self.paths[i] def pop(self, i=-1): """Delete and return a path""" r = self.paths[i] del self[i] return r
class ImageStack(TextureStack): '''Instead of supplying textures themselves, supply paths to where the textures may be loaded from. ''' def on_paths(self, *args): '''Make textures from the images in ``paths``, and assign them at the same index in my ``texs`` as in my ``paths``. ''' pass def clear(self): '''Clear paths, textures, rectangles''' pass def insert(self, i, v): '''Insert a string to my paths''' pass def __delitem__(self, i): '''Delete texture, rectangle, path''' pass def pop(self, i=-1): '''Delete and return a path''' pass
6
6
9
0
7
1
2
0.32
1
5
0
2
5
0
5
16
62
8
41
12
35
13
31
11
25
6
2
3
11
146,682
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/imagestackproxy.py
elide.imagestackproxy.ImageStackProxy
class ImageStackProxy(ImageStack): proxy = ObjectProperty() name = ObjectProperty() def finalize(self, initial=True): if getattr(self, "_finalized", False): return if self.proxy is None or not hasattr(self.proxy, "name"): Clock.schedule_once(self.finalize, 0) return if initial: self.name = self.proxy.name if "_image_paths" in self.proxy: try: self.paths = self.proxy["_image_paths"] except Exception as ex: if not ex.args[0].startswith("Unable to load image type"): raise ex self.paths = self.default_image_paths else: self.paths = self.proxy.setdefault( "_image_paths", self.default_image_paths ) self.finalize_children(initial) self._paths_binding = self.fbind( "paths", self._trigger_push_image_paths ) self._offxs_binding = self.fbind("offxs", self._trigger_push_offxs) self._offys_binding = self.fbind("offys", self._trigger_push_offys) self._finalized = True def finalize_children(self, initial=True, *_): for child in self.children: if not getattr(child, "_finalized", False): child.finalize(initial=initial) def unfinalize(self): self.unbind_uid("paths", self._paths_binding) self.unbind_uid("offxs", self._offxs_binding) self.unbind_uid("offys", self._offys_binding) self._finalized = False def pull_from_proxy(self, *_): initial = not hasattr(self, "_finalized") self.unfinalize() for key, att in [ ("_image_paths", "paths"), ("_offxs", "offxs"), ("_offys", "offys"), ]: if key in self.proxy and self.proxy[key] != getattr(self, att): setattr(self, att, self.proxy[key]) self.finalize(initial) def _trigger_pull_from_proxy(self, *args, **kwargs): if hasattr(self, "_scheduled_pull_from_proxy"): Clock.unschedule(self._scheduled_pull_from_proxy) self._scheduled_pull_from_proxy = Clock.schedule_once( self.pull_from_proxy, 0 ) @trigger def _trigger_push_image_paths(self, *_): self.proxy["_image_paths"] = list(self.paths) @trigger def _trigger_push_offxs(self, *_): self.proxy["_offxs"] = list(self.offxs) @trigger def _trigger_push_offys(self, *_): self.proxy["_offys"] = list(self.offys) @trigger def _trigger_push_stackhs(self, *_): self.proxy["_stackhs"] = list(self.stackhs) @trigger def restack(self, *_): childs = sorted( list(self.children), key=lambda child: child.priority, reverse=True ) self.clear_widgets() for child in childs: self.add_widget(child) self.do_layout()
class ImageStackProxy(ImageStack): def finalize(self, initial=True): pass def finalize_children(self, initial=True, *_): pass def unfinalize(self): pass def pull_from_proxy(self, *_): pass def _trigger_pull_from_proxy(self, *args, **kwargs): pass @trigger def _trigger_push_image_paths(self, *_): pass @trigger def _trigger_push_offxs(self, *_): pass @trigger def _trigger_push_offys(self, *_): pass @trigger def _trigger_push_stackhs(self, *_): pass @trigger def restack(self, *_): pass
16
0
7
0
7
0
2
0
1
2
0
1
10
7
10
26
86
10
76
31
60
0
58
24
47
7
3
4
22
146,683
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/grid/board.py
elide.grid.board.GridSpot
class GridSpot(Stack): default_image_paths = ["atlas://rltiles/floor.atlas/floor-stone"] @property def _stack_plane(self): return self.board.spot_plane
class GridSpot(Stack): @property def _stack_plane(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
31
6
1
5
4
2
0
4
3
2
1
1
0
1
146,684
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/pawn.py
elide.pawn.PawnBehavior
class PawnBehavior: """Mix-in class for things in places represented graphically""" loc_name = ObjectProperty() default_image_paths = ["atlas://rltiles/base.atlas/unseen"] priority = NumericProperty() board = ObjectProperty() def __init__(self, **kwargs): if "thing" in kwargs: kwargs["proxy"] = kwargs["thing"] del kwargs["thing"] if "proxy" in kwargs: kwargs["loc_name"] = kwargs["proxy"]["location"] super().__init__(**kwargs) self.register_event_type("on_drop") def on_proxy(self, *args): self.loc_name = self.proxy["location"] def on_parent(self, *args): if not self.parent: Clock.schedule_once(self.on_parent, 0) return self.board = self.parent.board self._relocate_binding = self.fbind("loc_name", self._trigger_relocate) if self.proxy: self._trigger_relocate() def finalize(self, initial=True): if initial: self.loc_name = self.proxy["location"] self.priority = self.proxy.get("_priority", 0.0) self._push_loc_binding = self.fbind( "loc_name", self._trigger_push_location ) super().finalize(initial) def unfinalize(self): self.unbind_uid("loc_name", self._push_loc_binding) super().unfinalize() def pull_from_proxy(self, *args): super().pull_from_proxy(*args) relocate = False if self.loc_name != self.proxy["location"]: self.unfinalize() self.unbind_uid("loc_name", self._relocate_binding) self.loc_name = self.proxy["location"] self._relocate_binding = self.fbind( "loc_name", self._trigger_relocate ) self.finalize(initial=False) relocate = True if "_priority" in self.proxy: self.priority = self.proxy["_priority"] if relocate: self.relocate() def relocate(self, *args): if ( not getattr(self, "_finalized", False) or not self.parent or not self.proxy or not self.proxy.exists ): return try: location = self._get_location_wid() except KeyError: return if location != self.parent: if self.parent: self.parent.remove_widget(self) location.add_widget(self) _trigger_relocate = trigger(relocate) def on_priority(self, *args): if self.proxy["_priority"] != self.priority: self.proxy["_priority"] = self.priority self.parent.restack() def push_location(self, *args): if self.proxy["location"] != self.loc_name: self.proxy["location"] = self.loc_name _trigger_push_location = trigger(push_location) def _get_location_wid(self): return self.board.spot[self.loc_name] def on_touch_up(self, touch): if touch.grab_current is not self: return False for spot in self.board.spot.values(): if self.collide_widget(spot) and spot.name != self.loc_name: new_spot = spot break else: new_spot = None self.dispatch("on_drop", new_spot) touch.ungrab(self) return True def on_drop(self, spot): parent = self.parent if spot: self.loc_name = self.proxy["location"] = spot.name parent.remove_widget(self) spot.add_widget(self) else: x, y = getattr(self, "rel_pos", (0, 0)) self.pos = parent.x + x, parent.y + y
class PawnBehavior: '''Mix-in class for things in places represented graphically''' def __init__(self, **kwargs): pass def on_proxy(self, *args): pass def on_parent(self, *args): pass def finalize(self, initial=True): pass def unfinalize(self): pass def pull_from_proxy(self, *args): pass def relocate(self, *args): pass def on_priority(self, *args): pass def push_location(self, *args): pass def _get_location_wid(self): pass def on_touch_up(self, touch): pass def on_drop(self, spot): pass
13
1
8
0
8
0
3
0.01
0
2
0
1
12
3
12
12
115
16
98
28
85
1
88
28
75
5
0
2
30
146,685
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/newmessage.py
telethon.events.newmessage.NewMessage
class NewMessage(EventBuilder): """ Occurs whenever a new text message or a message with media arrives. Args: incoming (`bool`, optional): If set to `True`, only **incoming** messages will be handled. Mutually exclusive with ``outgoing`` (can only set one of either). outgoing (`bool`, optional): If set to `True`, only **outgoing** messages will be handled. Mutually exclusive with ``incoming`` (can only set one of either). from_users (`entity`, optional): Unlike `chats`, this parameter filters the *senders* of the message. That is, only messages *sent by these users* will be handled. Use `chats` if you want private messages with this/these users. `from_users` lets you filter by messages sent by *one or more* users across the desired chats (doesn't need a list). forwards (`bool`, optional): Whether forwarded messages should be handled or not. By default, both forwarded and normal messages are included. If it's `True` *only* forwards will be handled. If it's `False` only messages that are *not* forwards will be handled. pattern (`str`, `callable`, `Pattern`, optional): If set, only messages matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns `True` if a message is acceptable, or a compiled regex pattern. Example .. code-block:: python import asyncio from telethon import events @client.on(events.NewMessage(pattern='(?i)hello.+')) async def handler(event): # Respond whenever someone says "Hello" and something else await event.reply('Hey!') @client.on(events.NewMessage(outgoing=True, pattern='!ping')) async def handler(event): # Say "!pong" whenever you send "!ping", then delete both messages m = await event.respond('!pong') await asyncio.sleep(5) await client.delete_messages(event.chat_id, [event.id, m.id]) """ def __init__(self, chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None): if incoming and outgoing: incoming = outgoing = None # Same as no filter elif incoming is not None and outgoing is None: outgoing = not incoming elif outgoing is not None and incoming is None: incoming = not outgoing elif all(x is not None and not x for x in (incoming, outgoing)): raise ValueError("Don't create an event handler if you " "don't want neither incoming nor outgoing!") super().__init__(chats, blacklist_chats=blacklist_chats, func=func) self.incoming = incoming self.outgoing = outgoing self.from_users = from_users self.forwards = forwards if isinstance(pattern, str): self.pattern = re.compile(pattern).match elif not pattern or callable(pattern): self.pattern = pattern elif hasattr(pattern, 'match') and callable(pattern.match): self.pattern = pattern.match else: raise TypeError('Invalid pattern type given') # Should we short-circuit? E.g. perform no check at all self._no_check = all(x is None for x in ( self.chats, self.incoming, self.outgoing, self.pattern, self.from_users, self.forwards, self.from_users, self.func )) async def _resolve(self, client): await super()._resolve(client) self.from_users = await _into_id_set(client, self.from_users) @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): if not isinstance(update.message, types.Message): return # We don't care about MessageService's here event = cls.Event(update.message) elif isinstance(update, types.UpdateShortMessage): event = cls.Event(types.Message( out=update.out, mentioned=update.mentioned, media_unread=update.media_unread, silent=update.silent, id=update.id, peer_id=types.PeerUser(update.user_id), from_id=types.PeerUser(self_id if update.out else update.user_id), message=update.message, date=update.date, fwd_from=update.fwd_from, via_bot_id=update.via_bot_id, reply_to=update.reply_to, entities=update.entities, ttl_period=update.ttl_period )) elif isinstance(update, types.UpdateShortChatMessage): event = cls.Event(types.Message( out=update.out, mentioned=update.mentioned, media_unread=update.media_unread, silent=update.silent, id=update.id, from_id=types.PeerUser(self_id if update.out else update.from_id), peer_id=types.PeerChat(update.chat_id), message=update.message, date=update.date, fwd_from=update.fwd_from, via_bot_id=update.via_bot_id, reply_to=update.reply_to, entities=update.entities, ttl_period=update.ttl_period )) else: return return event def filter(self, event): if self._no_check: return event if self.incoming and event.message.out: return if self.outgoing and not event.message.out: return if self.forwards is not None: if bool(self.forwards) != bool(event.message.fwd_from): return if self.from_users is not None: if event.message.sender_id not in self.from_users: return if self.pattern: match = self.pattern(event.message.message or '') if not match: return event.pattern_match = match return super().filter(event) class Event(EventCommon): """ Represents the event of a new message. This event can be treated to all effects as a `Message <telethon.tl.custom.message.Message>`, so please **refer to its documentation** to know what you can do with this event. Members: message (`Message <telethon.tl.custom.message.Message>`): This is the only difference with the received `Message <telethon.tl.custom.message.Message>`, and will return the `telethon.tl.custom.message.Message` itself, not the text. See `Message <telethon.tl.custom.message.Message>` for the rest of available members and methods. pattern_match (`obj`): The resulting object from calling the passed ``pattern`` function. Here's an example using a string (defaults to regex match): >>> from telethon import TelegramClient, events >>> client = TelegramClient(...) >>> >>> @client.on(events.NewMessage(pattern=r'hi (\\w+)!')) ... async def handler(event): ... # In this case, the result is a ``Match`` object ... # since the `str` pattern was converted into ... # the ``re.compile(pattern).match`` function. ... print('Welcomed', event.pattern_match.group(1)) ... >>> """ def __init__(self, message): self.__dict__['_init'] = False super().__init__(chat_peer=message.peer_id, msg_id=message.id, broadcast=bool(message.post)) self.pattern_match = None self.message = message def _set_client(self, client): super()._set_client(client) m = self.message m._finish_init(client, self._entities, None) self.__dict__['_init'] = True # No new attributes can be set def __getattr__(self, item): if item in self.__dict__: return self.__dict__[item] else: return getattr(self.message, item) def __setattr__(self, name, value): if not self.__dict__['_init'] or name in self.__dict__: self.__dict__[name] = value else: setattr(self.message, name, value)
class NewMessage(EventBuilder): ''' Occurs whenever a new text message or a message with media arrives. Args: incoming (`bool`, optional): If set to `True`, only **incoming** messages will be handled. Mutually exclusive with ``outgoing`` (can only set one of either). outgoing (`bool`, optional): If set to `True`, only **outgoing** messages will be handled. Mutually exclusive with ``incoming`` (can only set one of either). from_users (`entity`, optional): Unlike `chats`, this parameter filters the *senders* of the message. That is, only messages *sent by these users* will be handled. Use `chats` if you want private messages with this/these users. `from_users` lets you filter by messages sent by *one or more* users across the desired chats (doesn't need a list). forwards (`bool`, optional): Whether forwarded messages should be handled or not. By default, both forwarded and normal messages are included. If it's `True` *only* forwards will be handled. If it's `False` only messages that are *not* forwards will be handled. pattern (`str`, `callable`, `Pattern`, optional): If set, only messages matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns `True` if a message is acceptable, or a compiled regex pattern. Example .. code-block:: python import asyncio from telethon import events @client.on(events.NewMessage(pattern='(?i)hello.+')) async def handler(event): # Respond whenever someone says "Hello" and something else await event.reply('Hey!') @client.on(events.NewMessage(outgoing=True, pattern='!ping')) async def handler(event): # Say "!pong" whenever you send "!ping", then delete both messages m = await event.respond('!pong') await asyncio.sleep(5) await client.delete_messages(event.chat_id, [event.id, m.id]) ''' def __init__(self, chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None): pass async def _resolve(self, client): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass class Event(EventCommon): ''' Represents the event of a new message. This event can be treated to all effects as a `Message <telethon.tl.custom.message.Message>`, so please **refer to its documentation** to know what you can do with this event. Members: message (`Message <telethon.tl.custom.message.Message>`): This is the only difference with the received `Message <telethon.tl.custom.message.Message>`, and will return the `telethon.tl.custom.message.Message` itself, not the text. See `Message <telethon.tl.custom.message.Message>` for the rest of available members and methods. pattern_match (`obj`): The resulting object from calling the passed ``pattern`` function. Here's an example using a string (defaults to regex match): >>> from telethon import TelegramClient, events >>> client = TelegramClient(...) >>> >>> @client.on(events.NewMessage(pattern=r'hi (\w+)!')) ... async def handler(event): ... # In this case, the result is a ``Match`` object ... # since the `str` pattern was converted into ... # the ``re.compile(pattern).match`` function. ... print('Welcomed', event.pattern_match.group(1)) ... >>> ''' def __init__(self, chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None): pass def _set_client(self, client): pass def __getattr__(self, item): pass def __setattr__(self, name, value): pass
11
2
16
1
14
1
4
0.61
1
5
0
1
3
6
4
29
215
28
118
24
105
72
68
21
58
10
5
2
32
146,686
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/raw.py
telethon.events.raw.Raw
class Raw(EventBuilder): """ Raw events are not actual events. Instead, they are the raw :tl:`Update` object that Telegram sends. You normally shouldn't need these. Args: types (`list` | `tuple` | `type`, optional): The type or types that the :tl:`Update` instance must be. Equivalent to ``if not isinstance(update, types): return``. Example .. code-block:: python from telethon import events @client.on(events.Raw) async def handler(update): # Print all incoming updates print(update.stringify()) """ def __init__(self, types=None, *, func=None): super().__init__(func=func) if not types: self.types = None elif not utils.is_list_like(types): if not isinstance(types, type): raise TypeError('Invalid input type given: {}'.format(types)) self.types = types else: if not all(isinstance(x, type) for x in types): raise TypeError('Invalid input types given: {}'.format(types)) self.types = tuple(types) async def resolve(self, client): self.resolved = True @classmethod def build(cls, update, others=None, self_id=None): return update def filter(self, event): if not self.types or isinstance(event, self.types): if self.func: # Return the result of func directly as it may need to be awaited return self.func(event) return event
class Raw(EventBuilder): ''' Raw events are not actual events. Instead, they are the raw :tl:`Update` object that Telegram sends. You normally shouldn't need these. Args: types (`list` | `tuple` | `type`, optional): The type or types that the :tl:`Update` instance must be. Equivalent to ``if not isinstance(update, types): return``. Example .. code-block:: python from telethon import events @client.on(events.Raw) async def handler(update): # Print all incoming updates print(update.stringify()) ''' def __init__(self, types=None, *, func=None): pass async def resolve(self, client): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass
6
1
6
1
5
0
3
0.74
1
3
0
0
3
2
4
29
49
9
23
8
17
17
20
7
15
5
5
2
10
146,687
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/album.py
telethon.events.album.AlbumHack
class AlbumHack: """ When receiving an album from a different data-center, they will come in separate `Updates`, so we need to temporarily remember them for a while and only after produce the event. Of course events are not designed for this kind of wizardy, so this is a dirty hack that gets the job done. When cleaning up the code base we may want to figure out a better way to do this, or just leave the album problem to the users; the update handling code is bad enough as it is. """ def __init__(self, client, event): # It's probably silly to use a weakref here because this object is # very short-lived but might as well try to do "the right thing". self._client = weakref.ref(client) self._event = event # parent event self._due = client.loop.time() + _HACK_DELAY client.loop.create_task(self.deliver_event()) def extend(self, messages): client = self._client() if client: # weakref may be dead self._event.messages.extend(messages) self._due = client.loop.time() + _HACK_DELAY async def deliver_event(self): while True: client = self._client() if client is None: return # weakref is dead, nothing to deliver diff = self._due - client.loop.time() if diff <= 0: # We've hit our due time, deliver event. It won't respect # sequential updates but fixing that would just worsen this. await client._dispatch_event(self._event) return del client # Clear ref and sleep until our due time await asyncio.sleep(diff)
class AlbumHack: ''' When receiving an album from a different data-center, they will come in separate `Updates`, so we need to temporarily remember them for a while and only after produce the event. Of course events are not designed for this kind of wizardy, so this is a dirty hack that gets the job done. When cleaning up the code base we may want to figure out a better way to do this, or just leave the album problem to the users; the update handling code is bad enough as it is. ''' def __init__(self, client, event): pass def extend(self, messages): pass async def deliver_event(self): pass
4
1
9
1
7
3
2
0.82
0
0
0
0
3
3
3
3
43
7
22
10
18
18
22
10
18
4
0
2
7
146,688
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/messageedited.py
telethon.events.messageedited.MessageEdited
class MessageEdited(NewMessage): """ Occurs whenever a message is edited. Just like `NewMessage <telethon.events.newmessage.NewMessage>`, you should treat this event as a `Message <telethon.tl.custom.message.Message>`. .. warning:: On channels, `Message.out <telethon.tl.custom.message.Message>` will be `True` if you sent the message originally, **not if you edited it**! This can be dangerous if you run outgoing commands on edits. Some examples follow: * You send a message "A", ``out is True``. * You edit "A" to "B", ``out is True``. * Someone else edits "B" to "C", ``out is True`` (**be careful!**). * Someone sends "X", ``out is False``. * Someone edits "X" to "Y", ``out is False``. * You edit "Y" to "Z", ``out is False``. Since there are useful cases where you need the right ``out`` value, the library cannot do anything automatically to help you. Instead, consider using ``from_users='me'`` (it won't work in broadcast channels at all since the sender is the channel and not you). Example .. code-block:: python from telethon import events @client.on(events.MessageEdited) async def handler(event): # Log the date of new edits print('Message', event.id, 'changed at', event.date) """ @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, (types.UpdateEditMessage, types.UpdateEditChannelMessage)): return cls.Event(update.message) class Event(NewMessage.Event): pass
class MessageEdited(NewMessage): ''' Occurs whenever a message is edited. Just like `NewMessage <telethon.events.newmessage.NewMessage>`, you should treat this event as a `Message <telethon.tl.custom.message.Message>`. .. warning:: On channels, `Message.out <telethon.tl.custom.message.Message>` will be `True` if you sent the message originally, **not if you edited it**! This can be dangerous if you run outgoing commands on edits. Some examples follow: * You send a message "A", ``out is True``. * You edit "A" to "B", ``out is True``. * Someone else edits "B" to "C", ``out is True`` (**be careful!**). * Someone sends "X", ``out is False``. * Someone edits "X" to "Y", ``out is False``. * You edit "Y" to "Z", ``out is False``. Since there are useful cases where you need the right ``out`` value, the library cannot do anything automatically to help you. Instead, consider using ``from_users='me'`` (it won't work in broadcast channels at all since the sender is the channel and not you). Example .. code-block:: python from telethon import events @client.on(events.MessageEdited) async def handler(event): # Log the date of new edits print('Message', event.id, 'changed at', event.date) ''' @classmethod def build(cls, update, others=None, self_id=None): pass class Event(NewMessage.Event):
4
1
4
0
4
0
2
3.75
1
0
0
0
0
0
1
30
46
9
8
4
4
30
6
3
3
2
6
1
2
146,689
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/messagedeleted.py
telethon.events.messagedeleted.MessageDeleted
class MessageDeleted(EventBuilder): """ Occurs whenever a message is deleted. Note that this event isn't 100% reliable, since Telegram doesn't always notify the clients that a message was deleted. .. important:: Telegram **does not** send information about *where* a message was deleted if it occurs in private conversations with other users or in small group chats, because message IDs are *unique* and you can identify the chat with the message ID alone if you saved it previously. Telethon **does not** save information of where messages occur, so it cannot know in which chat a message was deleted (this will only work in channels, where the channel ID *is* present). This means that the ``chats=`` parameter will not work reliably, unless you intend on working with channels and super-groups only. Example .. code-block:: python from telethon import events @client.on(events.MessageDeleted) async def handler(event): # Log all deleted message IDs for msg_id in event.deleted_ids: print('Message', msg_id, 'was deleted in', event.chat_id) """ @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, types.UpdateDeleteMessages): return cls.Event( deleted_ids=update.messages, peer=None ) elif isinstance(update, types.UpdateDeleteChannelMessages): return cls.Event( deleted_ids=update.messages, peer=types.PeerChannel(update.channel_id) ) class Event(EventCommon): def __init__(self, deleted_ids, peer): super().__init__( chat_peer=peer, msg_id=(deleted_ids or [0])[0] ) self.deleted_id = None if not deleted_ids else deleted_ids[0] self.deleted_ids = deleted_ids
class MessageDeleted(EventBuilder): ''' Occurs whenever a message is deleted. Note that this event isn't 100% reliable, since Telegram doesn't always notify the clients that a message was deleted. .. important:: Telegram **does not** send information about *where* a message was deleted if it occurs in private conversations with other users or in small group chats, because message IDs are *unique* and you can identify the chat with the message ID alone if you saved it previously. Telethon **does not** save information of where messages occur, so it cannot know in which chat a message was deleted (this will only work in channels, where the channel ID *is* present). This means that the ``chats=`` parameter will not work reliably, unless you intend on working with channels and super-groups only. Example .. code-block:: python from telethon import events @client.on(events.MessageDeleted) async def handler(event): # Log all deleted message IDs for msg_id in event.deleted_ids: print('Message', msg_id, 'was deleted in', event.chat_id) ''' @classmethod def build(cls, update, others=None, self_id=None): pass class Event(EventCommon): def __init__(self, deleted_ids, peer): pass
5
1
9
0
9
0
3
1.2
1
0
0
0
0
0
1
26
52
8
20
7
15
24
10
6
6
3
5
1
5
146,690
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/inlinequery.py
telethon.events.inlinequery.InlineQuery
class InlineQuery(EventBuilder): """ Occurs whenever you sign in as a bot and a user sends an inline query such as ``@bot query``. Args: users (`entity`, optional): May be one or more entities (username/peer/etc.), preferably IDs. By default, only inline queries from these users will be handled. blacklist_users (`bool`, optional): Whether to treat the users as a blacklist instead of as a whitelist (default). This means that every chat will be handled *except* those specified in ``users`` which will be ignored if ``blacklist_users=True``. pattern (`str`, `callable`, `Pattern`, optional): If set, only queries matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns `True` if a message is acceptable, or a compiled regex pattern. Example .. code-block:: python from telethon import events @client.on(events.InlineQuery) async def handler(event): builder = event.builder # Two options (convert user text to UPPERCASE or lowercase) await event.answer([ builder.article('UPPERCASE', text=event.text.upper()), builder.article('lowercase', text=event.text.lower()), ]) """ def __init__( self, users=None, *, blacklist_users=False, func=None, pattern=None): super().__init__(users, blacklist_chats=blacklist_users, func=func) if isinstance(pattern, str): self.pattern = re.compile(pattern).match elif not pattern or callable(pattern): self.pattern = pattern elif hasattr(pattern, 'match') and callable(pattern.match): self.pattern = pattern.match else: raise TypeError('Invalid pattern type given') @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, types.UpdateBotInlineQuery): return cls.Event(update) def filter(self, event): if self.pattern: match = self.pattern(event.text) if not match: return event.pattern_match = match return super().filter(event) class Event(EventCommon, SenderGetter): """ Represents the event of a new callback query. Members: query (:tl:`UpdateBotInlineQuery`): The original :tl:`UpdateBotInlineQuery`. Make sure to access the `text` property of the query if you want the text rather than the actual query object. pattern_match (`obj`, optional): The resulting object from calling the passed ``pattern`` function, which is ``re.compile(...).match`` by default. """ def __init__(self, query): super().__init__(chat_peer=types.PeerUser(query.user_id)) SenderGetter.__init__(self, query.user_id) self.query = query self.pattern_match = None self._answered = False def _set_client(self, client): super()._set_client(client) self._sender, self._input_sender = utils._get_entity_pair( self.sender_id, self._entities, client._mb_entity_cache) @property def id(self): """ Returns the unique identifier for the query ID. """ return self.query.query_id @property def text(self): """ Returns the text the user used to make the inline query. """ return self.query.query @property def offset(self): """ The string the user's client used as an offset for the query. This will either be empty or equal to offsets passed to `answer`. """ return self.query.offset @property def geo(self): """ If the user location is requested when using inline mode and the user's device is able to send it, this will return the :tl:`GeoPoint` with the position of the user. """ return self.query.geo @property def builder(self): """ Returns a new `InlineBuilder <telethon.tl.custom.inlinebuilder.InlineBuilder>` instance. """ return custom.InlineBuilder(self._client) async def answer( self, results=None, cache_time=0, *, gallery=False, next_offset=None, private=False, switch_pm=None, switch_pm_param=''): """ Answers the inline query with the given results. See the documentation for `builder` to know what kind of answers can be given. Args: results (`list`, optional): A list of :tl:`InputBotInlineResult` to use. You should use `builder` to create these: .. code-block:: python builder = inline.builder r1 = builder.article('Be nice', text='Have a nice day') r2 = builder.article('Be bad', text="I don't like you") await inline.answer([r1, r2]) You can send up to 50 results as documented in https://core.telegram.org/bots/api#answerinlinequery. Sending more will raise ``ResultsTooMuchError``, and you should consider using `next_offset` to paginate them. cache_time (`int`, optional): For how long this result should be cached on the user's client. Defaults to 0 for no cache. gallery (`bool`, optional): Whether the results should show as a gallery (grid) or not. next_offset (`str`, optional): The offset the client will send when the user scrolls the results and it repeats the request. private (`bool`, optional): Whether the results should be cached by Telegram (not private) or by the user's client (private). switch_pm (`str`, optional): If set, this text will be shown in the results to allow the user to switch to private messages. switch_pm_param (`str`, optional): Optional parameter to start the bot with if `switch_pm` was used. Example: .. code-block:: python @bot.on(events.InlineQuery) async def handler(event): builder = event.builder rev_text = event.text[::-1] await event.answer([ builder.article('Reverse text', text=rev_text), builder.photo('/path/to/photo.jpg') ]) """ if self._answered: return if results: futures = [self._as_future(x) for x in results] await asyncio.wait(futures) # All futures will be in the `done` *set* that `wait` returns. # # Precisely because it's a `set` and not a `list`, it # will not preserve the order, but since all futures # completed we can use our original, ordered `list`. results = [x.result() for x in futures] else: results = [] if switch_pm: switch_pm = types.InlineBotSwitchPM(switch_pm, switch_pm_param) return await self._client( functions.messages.SetInlineBotResultsRequest( query_id=self.query.query_id, results=results, cache_time=cache_time, gallery=gallery, next_offset=next_offset, private=private, switch_pm=switch_pm ) ) @staticmethod def _as_future(obj): if inspect.isawaitable(obj): return asyncio.ensure_future(obj) f = helpers.get_running_loop().create_future() f.set_result(obj) return f
class InlineQuery(EventBuilder): ''' Occurs whenever you sign in as a bot and a user sends an inline query such as ``@bot query``. Args: users (`entity`, optional): May be one or more entities (username/peer/etc.), preferably IDs. By default, only inline queries from these users will be handled. blacklist_users (`bool`, optional): Whether to treat the users as a blacklist instead of as a whitelist (default). This means that every chat will be handled *except* those specified in ``users`` which will be ignored if ``blacklist_users=True``. pattern (`str`, `callable`, `Pattern`, optional): If set, only queries matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns `True` if a message is acceptable, or a compiled regex pattern. Example .. code-block:: python from telethon import events @client.on(events.InlineQuery) async def handler(event): builder = event.builder # Two options (convert user text to UPPERCASE or lowercase) await event.answer([ builder.article('UPPERCASE', text=event.text.upper()), builder.article('lowercase', text=event.text.lower()), ]) ''' def __init__( self, users=None, *, blacklist_users=False, func=None, pattern=None): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass class Event(EventCommon, SenderGetter): ''' Represents the event of a new callback query. Members: query (:tl:`UpdateBotInlineQuery`): The original :tl:`UpdateBotInlineQuery`. Make sure to access the `text` property of the query if you want the text rather than the actual query object. pattern_match (`obj`, optional): The resulting object from calling the passed ``pattern`` function, which is ``re.compile(...).match`` by default. ''' def __init__( self, users=None, *, blacklist_users=False, func=None, pattern=None): pass def _set_client(self, client): pass @property def id(self): ''' Returns the unique identifier for the query ID. ''' pass @property def text(self): ''' Returns the text the user used to make the inline query. ''' pass @property def offset(self): ''' The string the user's client used as an offset for the query. This will either be empty or equal to offsets passed to `answer`. ''' pass @property def geo(self): ''' If the user location is requested when using inline mode and the user's device is able to send it, this will return the :tl:`GeoPoint` with the position of the user. ''' pass @property def builder(self): ''' Returns a new `InlineBuilder <telethon.tl.custom.inlinebuilder.InlineBuilder>` instance. ''' pass async def answer( self, results=None, cache_time=0, *, gallery=False, next_offset=None, private=False, switch_pm=None, switch_pm_param=''): ''' Answers the inline query with the given results. See the documentation for `builder` to know what kind of answers can be given. Args: results (`list`, optional): A list of :tl:`InputBotInlineResult` to use. You should use `builder` to create these: .. code-block:: python builder = inline.builder r1 = builder.article('Be nice', text='Have a nice day') r2 = builder.article('Be bad', text="I don't like you") await inline.answer([r1, r2]) You can send up to 50 results as documented in https://core.telegram.org/bots/api#answerinlinequery. Sending more will raise ``ResultsTooMuchError``, and you should consider using `next_offset` to paginate them. cache_time (`int`, optional): For how long this result should be cached on the user's client. Defaults to 0 for no cache. gallery (`bool`, optional): Whether the results should show as a gallery (grid) or not. next_offset (`str`, optional): The offset the client will send when the user scrolls the results and it repeats the request. private (`bool`, optional): Whether the results should be cached by Telegram (not private) or by the user's client (private). switch_pm (`str`, optional): If set, this text will be shown in the results to allow the user to switch to private messages. switch_pm_param (`str`, optional): Optional parameter to start the bot with if `switch_pm` was used. Example: .. code-block:: python @bot.on(events.InlineQuery) async def handler(event): builder = event.builder rev_text = event.text[::-1] await event.answer([ builder.article('Reverse text', text=rev_text), builder.photo('/path/to/photo.jpg') ]) ''' pass @staticmethod def _as_future(obj): pass
21
8
14
2
6
6
2
1.36
1
3
0
0
2
1
3
28
235
44
81
33
56
110
55
22
41
4
5
2
22
146,691
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/chataction.py
telethon.events.chataction.ChatAction
class ChatAction(EventBuilder): """ Occurs on certain chat actions: * Whenever a new chat is created. * Whenever a chat's title or photo is changed or removed. * Whenever a new message is pinned. * Whenever a user scores in a game. * Whenever a user joins or is added to the group. * Whenever a user is removed or leaves a group if it has less than 50 members or the removed user was a bot. Note that "chat" refers to "small group, megagroup and broadcast channel", whereas "group" refers to "small group and megagroup" only. Example .. code-block:: python from telethon import events @client.on(events.ChatAction) async def handler(event): # Welcome every new user if event.user_joined: await event.reply('Welcome to the group!') """ @classmethod def build(cls, update, others=None, self_id=None): # Rely on specific pin updates for unpins, but otherwise ignore them # for new pins (we'd rather handle the new service message with pin, # so that we can act on that message'). if isinstance(update, types.UpdatePinnedChannelMessages) and not update.pinned: return cls.Event(types.PeerChannel(update.channel_id), pin_ids=update.messages, pin=update.pinned) elif isinstance(update, types.UpdatePinnedMessages) and not update.pinned: return cls.Event(update.peer, pin_ids=update.messages, pin=update.pinned) elif isinstance(update, types.UpdateChatParticipantAdd): return cls.Event(types.PeerChat(update.chat_id), added_by=update.inviter_id or True, users=update.user_id) elif isinstance(update, types.UpdateChatParticipantDelete): return cls.Event(types.PeerChat(update.chat_id), kicked_by=True, users=update.user_id) # UpdateChannel is sent if we leave a channel, and the update._entities # set by _process_update would let us make some guesses. However it's # better not to rely on this. Rely only in MessageActionChatDeleteUser. elif (isinstance(update, ( types.UpdateNewMessage, types.UpdateNewChannelMessage)) and isinstance(update.message, types.MessageService)): msg = update.message action = update.message.action if isinstance(action, types.MessageActionChatJoinedByLink): return cls.Event(msg, added_by=True, users=msg.from_id) elif isinstance(action, types.MessageActionChatAddUser): # If a user adds itself, it means they joined via the public chat username added_by = ([msg.sender_id] == action.users) or msg.from_id return cls.Event(msg, added_by=added_by, users=action.users) elif isinstance(action, types.MessageActionChatDeleteUser): return cls.Event(msg, kicked_by=utils.get_peer_id(msg.from_id) if msg.from_id else True, users=action.user_id) elif isinstance(action, types.MessageActionChatCreate): return cls.Event(msg, users=action.users, created=True, new_title=action.title) elif isinstance(action, types.MessageActionChannelCreate): return cls.Event(msg, created=True, users=msg.from_id, new_title=action.title) elif isinstance(action, types.MessageActionChatEditTitle): return cls.Event(msg, users=msg.from_id, new_title=action.title) elif isinstance(action, types.MessageActionChatEditPhoto): return cls.Event(msg, users=msg.from_id, new_photo=action.photo) elif isinstance(action, types.MessageActionChatDeletePhoto): return cls.Event(msg, users=msg.from_id, new_photo=True) elif isinstance(action, types.MessageActionPinMessage) and msg.reply_to: return cls.Event(msg, pin_ids=[msg.reply_to_msg_id]) elif isinstance(action, types.MessageActionGameScore): return cls.Event(msg, new_score=action.score) elif isinstance(update, types.UpdateChannelParticipant) \ and bool(update.new_participant) != bool(update.prev_participant): # If members are hidden, bots will receive this update instead, # as there won't be a service message. Promotions and demotions # seem to have both new and prev participant, which are ignored # by this event. return cls.Event(types.PeerChannel(update.channel_id), users=update.user_id, added_by=update.actor_id if update.new_participant else None, kicked_by=update.actor_id if update.prev_participant else None) class Event(EventCommon): """ Represents the event of a new chat action. Members: action_message (`MessageAction <https://tl.telethon.dev/types/message_action.html>`_): The message invoked by this Chat Action. new_pin (`bool`): `True` if there is a new pin. new_photo (`bool`): `True` if there's a new chat photo (or it was removed). photo (:tl:`Photo`, optional): The new photo (or `None` if it was removed). user_added (`bool`): `True` if the user was added by some other. user_joined (`bool`): `True` if the user joined on their own. user_left (`bool`): `True` if the user left on their own. user_kicked (`bool`): `True` if the user was kicked by some other. created (`bool`, optional): `True` if this chat was just created. new_title (`str`, optional): The new title string for the chat, if applicable. new_score (`str`, optional): The new score string for the game, if applicable. unpin (`bool`): `True` if the existing pin gets unpinned. """ def __init__(self, where, new_photo=None, added_by=None, kicked_by=None, created=None, users=None, new_title=None, pin_ids=None, pin=None, new_score=None): if isinstance(where, types.MessageService): self.action_message = where where = where.peer_id else: self.action_message = None # TODO needs some testing (can there be more than one id, and do they follow pin order?) # same in get_pinned_message super().__init__(chat_peer=where, msg_id=pin_ids[0] if pin_ids else None) self.new_pin = pin_ids is not None self._pin_ids = pin_ids self._pinned_messages = None self.new_photo = new_photo is not None self.photo = \ new_photo if isinstance(new_photo, types.Photo) else None self._added_by = None self._kicked_by = None self.user_added = self.user_joined = self.user_left = \ self.user_kicked = self.unpin = False if added_by is True: self.user_joined = True elif added_by: self.user_added = True self._added_by = added_by # If `from_id` was not present (it's `True`) or the affected # user was "kicked by itself", then it left. Else it was kicked. if kicked_by is True or (users is not None and kicked_by == users): self.user_left = True elif kicked_by: self.user_kicked = True self._kicked_by = kicked_by self.created = bool(created) if isinstance(users, list): self._user_ids = [utils.get_peer_id(u) for u in users] elif users: self._user_ids = [utils.get_peer_id(users)] else: self._user_ids = [] self._users = None self._input_users = None self.new_title = new_title self.new_score = new_score self.unpin = not pin def _set_client(self, client): super()._set_client(client) if self.action_message: self.action_message._finish_init(client, self._entities, None) async def respond(self, *args, **kwargs): """ Responds to the chat action message (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. """ return await self._client.send_message( await self.get_input_chat(), *args, **kwargs) async def reply(self, *args, **kwargs): """ Replies to the chat action message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. Has the same effect as `respond` if there is no message. """ if not self.action_message: return await self.respond(*args, **kwargs) kwargs['reply_to'] = self.action_message.id return await self._client.send_message( await self.get_input_chat(), *args, **kwargs) async def delete(self, *args, **kwargs): """ Deletes the chat action message. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. Does nothing if no message action triggered this event. """ if not self.action_message: return return await self._client.delete_messages( await self.get_input_chat(), [self.action_message], *args, **kwargs ) async def get_pinned_message(self): """ If ``new_pin`` is `True`, this returns the `Message <telethon.tl.custom.message.Message>` object that was pinned. """ if self._pinned_messages is None: await self.get_pinned_messages() if self._pinned_messages: return self._pinned_messages[0] async def get_pinned_messages(self): """ If ``new_pin`` is `True`, this returns a `list` of `Message <telethon.tl.custom.message.Message>` objects that were pinned. """ if not self._pin_ids: return self._pin_ids # either None or empty list chat = await self.get_input_chat() if chat: self._pinned_messages = await self._client.get_messages( self._input_chat, ids=self._pin_ids) return self._pinned_messages @property def added_by(self): """ The user who added ``users``, if applicable (`None` otherwise). """ if self._added_by and not isinstance(self._added_by, types.User): aby = self._entities.get(utils.get_peer_id(self._added_by)) if aby: self._added_by = aby return self._added_by async def get_added_by(self): """ Returns `added_by` but will make an API call if necessary. """ if not self.added_by and self._added_by: self._added_by = await self._client.get_entity(self._added_by) return self._added_by @property def kicked_by(self): """ The user who kicked ``users``, if applicable (`None` otherwise). """ if self._kicked_by and not isinstance(self._kicked_by, types.User): kby = self._entities.get(utils.get_peer_id(self._kicked_by)) if kby: self._kicked_by = kby return self._kicked_by async def get_kicked_by(self): """ Returns `kicked_by` but will make an API call if necessary. """ if not self.kicked_by and self._kicked_by: self._kicked_by = await self._client.get_entity(self._kicked_by) return self._kicked_by @property def user(self): """ The first user that takes part in this action. For example, who joined. Might be `None` if the information can't be retrieved or there is no user taking part. """ if self.users: return self._users[0] async def get_user(self): """ Returns `user` but will make an API call if necessary. """ if self.users or await self.get_users(): return self._users[0] @property def input_user(self): """ Input version of the ``self.user`` property. """ if self.input_users: return self._input_users[0] async def get_input_user(self): """ Returns `input_user` but will make an API call if necessary. """ if self.input_users or await self.get_input_users(): return self._input_users[0] @property def user_id(self): """ Returns the marked signed ID of the first user, if any. """ if self._user_ids: return self._user_ids[0] @property def users(self): """ A list of users that take part in this action. For example, who joined. Might be empty if the information can't be retrieved or there are no users taking part. """ if not self._user_ids: return [] if self._users is None: self._users = [ self._entities[user_id] for user_id in self._user_ids if user_id in self._entities ] return self._users async def get_users(self): """ Returns `users` but will make an API call if necessary. """ if not self._user_ids: return [] # Note: we access the property first so that it fills if needed if (self.users is None or len(self._users) != len(self._user_ids)) and self.action_message: await self.action_message._reload_message() self._users = [ u for u in self.action_message.action_entities if isinstance(u, (types.User, types.UserEmpty))] return self._users @property def input_users(self): """ Input version of the ``self.users`` property. """ if self._input_users is None and self._user_ids: self._input_users = [] for user_id in self._user_ids: # First try to get it from our entities try: self._input_users.append(utils.get_input_peer(self._entities[user_id])) continue except (KeyError, TypeError): pass # If missing, try from the entity cache try: self._input_users.append(self._client._mb_entity_cache.get( utils.resolve_id(user_id)[0])._as_input_peer()) continue except AttributeError: pass return self._input_users or [] async def get_input_users(self): """ Returns `input_users` but will make an API call if necessary. """ if not self._user_ids: return [] # Note: we access the property first so that it fills if needed if (self.input_users is None or len(self._input_users) != len(self._user_ids)) and self.action_message: self._input_users = [ utils.get_input_peer(u) for u in self.action_message.action_entities if isinstance(u, (types.User, types.UserEmpty))] return self._input_users or [] @property def user_ids(self): """ Returns the marked signed ID of the users, if any. """ if self._user_ids: return self._user_ids[:]
class ChatAction(EventBuilder): ''' Occurs on certain chat actions: * Whenever a new chat is created. * Whenever a chat's title or photo is changed or removed. * Whenever a new message is pinned. * Whenever a user scores in a game. * Whenever a user joins or is added to the group. * Whenever a user is removed or leaves a group if it has less than 50 members or the removed user was a bot. Note that "chat" refers to "small group, megagroup and broadcast channel", whereas "group" refers to "small group and megagroup" only. Example .. code-block:: python from telethon import events @client.on(events.ChatAction) async def handler(event): # Welcome every new user if event.user_joined: await event.reply('Welcome to the group!') ''' @classmethod def build(cls, update, others=None, self_id=None): pass class Event(EventCommon): ''' Represents the event of a new chat action. Members: action_message (`MessageAction <https://tl.telethon.dev/types/message_action.html>`_): The message invoked by this Chat Action. new_pin (`bool`): `True` if there is a new pin. new_photo (`bool`): `True` if there's a new chat photo (or it was removed). photo (:tl:`Photo`, optional): The new photo (or `None` if it was removed). user_added (`bool`): `True` if the user was added by some other. user_joined (`bool`): `True` if the user joined on their own. user_left (`bool`): `True` if the user left on their own. user_kicked (`bool`): `True` if the user was kicked by some other. created (`bool`, optional): `True` if this chat was just created. new_title (`str`, optional): The new title string for the chat, if applicable. new_score (`str`, optional): The new score string for the game, if applicable. unpin (`bool`): `True` if the existing pin gets unpinned. ''' def __init__(self, where, new_photo=None, added_by=None, kicked_by=None, created=None, users=None, new_title=None, pin_ids=None, pin=None, new_score=None): pass def _set_client(self, client): pass async def respond(self, *args, **kwargs): ''' Responds to the chat action message (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. ''' pass async def reply(self, *args, **kwargs): ''' Replies to the chat action message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. Has the same effect as `respond` if there is no message. ''' pass async def delete(self, *args, **kwargs): ''' Deletes the chat action message. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. Does nothing if no message action triggered this event. ''' pass async def get_pinned_message(self): ''' If ``new_pin`` is `True`, this returns the `Message <telethon.tl.custom.message.Message>` object that was pinned. ''' pass async def get_pinned_messages(self): ''' If ``new_pin`` is `True`, this returns a `list` of `Message <telethon.tl.custom.message.Message>` objects that were pinned. ''' pass @property def added_by(self): ''' The user who added ``users``, if applicable (`None` otherwise). ''' pass async def get_added_by(self): ''' Returns `added_by` but will make an API call if necessary. ''' pass @property def kicked_by(self): ''' The user who kicked ``users``, if applicable (`None` otherwise). ''' pass async def get_kicked_by(self): ''' Returns `kicked_by` but will make an API call if necessary. ''' pass @property def user(self): ''' The first user that takes part in this action. For example, who joined. Might be `None` if the information can't be retrieved or there is no user taking part. ''' pass async def get_user(self): ''' Returns `user` but will make an API call if necessary. ''' pass @property def input_user(self): ''' Input version of the ``self.user`` property. ''' pass async def get_input_user(self): ''' Returns `input_user` but will make an API call if necessary. ''' pass @property def user_id(self): ''' Returns the marked signed ID of the first user, if any. ''' pass @property def users(self): ''' A list of users that take part in this action. For example, who joined. Might be empty if the information can't be retrieved or there are no users taking part. ''' pass async def get_users(self): ''' Returns `users` but will make an API call if necessary. ''' pass @property def input_users(self): ''' Input version of the ``self.users`` property. ''' pass async def get_input_users(self): ''' Returns `input_users` but will make an API call if necessary. ''' pass @property def user_ids(self): ''' Returns the marked signed ID of the users, if any. ''' pass
33
21
16
2
10
4
4
0.6
1
1
0
0
0
0
1
26
452
76
236
60
201
141
154
46
130
20
5
3
79
146,692
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/callbackquery.py
telethon.events.callbackquery.CallbackQuery
class CallbackQuery(EventBuilder): """ Occurs whenever you sign in as a bot and a user clicks one of the inline buttons on your messages. Note that the `chats` parameter will **not** work with normal IDs or peers if the clicked inline button comes from a "via bot" message. The `chats` parameter also supports checking against the `chat_instance` which should be used for inline callbacks. Args: data (`bytes`, `str`, `callable`, optional): If set, the inline button payload data must match this data. A UTF-8 string can also be given, a regex or a callable. For instance, to check against ``'data_1'`` and ``'data_2'`` you can use ``re.compile(b'data_')``. pattern (`bytes`, `str`, `callable`, `Pattern`, optional): If set, only buttons with payload matching this pattern will be handled. You can specify a regex-like string which will be matched against the payload data, a callable function that returns `True` if a the payload data is acceptable, or a compiled regex pattern. Example .. code-block:: python from telethon import events, Button # Handle all callback queries and check data inside the handler @client.on(events.CallbackQuery) async def handler(event): if event.data == b'yes': await event.answer('Correct answer!') # Handle only callback queries with data being b'no' @client.on(events.CallbackQuery(data=b'no')) async def handler(event): # Pop-up message with alert await event.answer('Wrong answer!', alert=True) # Send a message with buttons users can click async def main(): await client.send_message(user, 'Yes or no?', buttons=[ Button.inline('Yes!', b'yes'), Button.inline('Nope', b'no') ]) """ def __init__( self, chats=None, *, blacklist_chats=False, func=None, data=None, pattern=None): super().__init__(chats, blacklist_chats=blacklist_chats, func=func) if data and pattern: raise ValueError("Only pass either data or pattern not both.") if isinstance(data, str): data = data.encode('utf-8') if isinstance(pattern, str): pattern = pattern.encode('utf-8') match = data if data else pattern if isinstance(match, bytes): self.match = data if data else re.compile(pattern).match elif not match or callable(match): self.match = match elif hasattr(match, 'match') and callable(match.match): if not isinstance(getattr(match, 'pattern', b''), bytes): match = re.compile(match.pattern.encode('utf-8'), match.flags & (~re.UNICODE)) self.match = match.match else: raise TypeError('Invalid data or pattern type given') self._no_check = all(x is None for x in ( self.chats, self.func, self.match, )) @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, types.UpdateBotCallbackQuery): return cls.Event(update, update.peer, update.msg_id) elif isinstance(update, types.UpdateInlineBotCallbackQuery): # See https://github.com/LonamiWebs/Telethon/pull/1005 # The long message ID is actually just msg_id + peer_id mid, pid = struct.unpack('<ii', struct.pack('<q', update.msg_id.id)) peer = types.PeerChannel(-pid) if pid < 0 else types.PeerUser(pid) return cls.Event(update, peer, mid) def filter(self, event): # We can't call super().filter(...) because it ignores chat_instance if self._no_check: return event if self.chats is not None: inside = event.query.chat_instance in self.chats if event.chat_id: inside |= event.chat_id in self.chats if inside == self.blacklist_chats: return if self.match: if callable(self.match): event.data_match = event.pattern_match = self.match(event.query.data) if not event.data_match: return elif event.query.data != self.match: return if self.func: # Return the result of func directly as it may need to be awaited return self.func(event) return True class Event(EventCommon, SenderGetter): """ Represents the event of a new callback query. Members: query (:tl:`UpdateBotCallbackQuery`): The original :tl:`UpdateBotCallbackQuery`. data_match (`obj`, optional): The object returned by the ``data=`` parameter when creating the event builder, if any. Similar to ``pattern_match`` for the new message event. pattern_match (`obj`, optional): Alias for ``data_match``. """ def __init__(self, query, peer, msg_id): super().__init__(peer, msg_id=msg_id) SenderGetter.__init__(self, query.user_id) self.query = query self.data_match = None self.pattern_match = None self._message = None self._answered = False def _set_client(self, client): super()._set_client(client) self._sender, self._input_sender = utils._get_entity_pair( self.sender_id, self._entities, client._mb_entity_cache) @property def id(self): """ Returns the query ID. The user clicking the inline button is the one who generated this random ID. """ return self.query.query_id @property def message_id(self): """ Returns the message ID to which the clicked inline button belongs. """ return self._message_id @property def data(self): """ Returns the data payload from the original inline button. """ return self.query.data @property def chat_instance(self): """ Unique identifier for the chat where the callback occurred. Useful for high scores in games. """ return self.query.chat_instance async def get_message(self): """ Returns the message to which the clicked inline button belongs. """ if self._message is not None: return self._message try: chat = await self.get_input_chat() if self.is_channel else None self._message = await self._client.get_messages( chat, ids=self._message_id) except ValueError: return return self._message async def _refetch_sender(self): self._sender = self._entities.get(self.sender_id) if not self._sender: return self._input_sender = utils.get_input_peer(self._chat) if not getattr(self._input_sender, 'access_hash', True): # getattr with True to handle the InputPeerSelf() case try: self._input_sender = self._client._mb_entity_cache.get( utils.resolve_id(self._sender_id)[0])._as_input_peer() except AttributeError: m = await self.get_message() if m: self._sender = m._sender self._input_sender = m._input_sender async def answer( self, message=None, cache_time=0, *, url=None, alert=False): """ Answers the callback query (and stops the loading circle). Args: message (`str`, optional): The toast message to show feedback to the user. cache_time (`int`, optional): For how long this result should be cached on the user's client. Defaults to 0 for no cache. url (`str`, optional): The URL to be opened in the user's client. Note that the only valid URLs are those of games your bot has, or alternatively a 't.me/your_bot?start=xyz' parameter. alert (`bool`, optional): Whether an alert (a pop-up dialog) should be used instead of showing a toast. Defaults to `False`. """ if self._answered: return self._answered = True return await self._client( functions.messages.SetBotCallbackAnswerRequest( query_id=self.query.query_id, cache_time=cache_time, alert=alert, message=message, url=url ) ) @property def via_inline(self): """ Whether this callback was generated from an inline button sent via an inline query or not. If the bot sent the message itself with buttons, and one of those is clicked, this will be `False`. If a user sent the message coming from an inline query to the bot, and one of those is clicked, this will be `True`. If it's `True`, it's likely that the bot is **not** in the chat, so methods like `respond` or `delete` won't work (but `edit` will always work). """ return isinstance(self.query, types.UpdateInlineBotCallbackQuery) async def respond(self, *args, **kwargs): """ Responds to the message (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. """ self._client.loop.create_task(self.answer()) return await self._client.send_message( await self.get_input_chat(), *args, **kwargs) async def reply(self, *args, **kwargs): """ Replies to the message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. """ self._client.loop.create_task(self.answer()) kwargs['reply_to'] = self.query.msg_id return await self._client.send_message( await self.get_input_chat(), *args, **kwargs) async def edit(self, *args, **kwargs): """ Edits the message. Shorthand for `telethon.client.messages.MessageMethods.edit_message` with the ``entity`` set to the correct :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64`. Returns `True` if the edit was successful. This method also creates a task to `answer` the callback. .. note:: This method won't respect the previous message unlike `Message.edit <telethon.tl.custom.message.Message.edit>`, since the message object is normally not present. """ self._client.loop.create_task(self.answer()) if isinstance(self.query.msg_id, (types.InputBotInlineMessageID, types.InputBotInlineMessageID64)): return await self._client.edit_message( self.query.msg_id, *args, **kwargs ) else: return await self._client.edit_message( await self.get_input_chat(), self.query.msg_id, *args, **kwargs ) async def delete(self, *args, **kwargs): """ Deletes the message. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. If you need to delete more than one message at once, don't use this `delete` method. Use a `telethon.client.telegramclient.TelegramClient` instance directly. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. """ self._client.loop.create_task(self.answer()) if isinstance(self.query.msg_id, (types.InputBotInlineMessageID, types.InputBotInlineMessageID64)): raise TypeError('Inline messages cannot be deleted as there is no API request available to do so') return await self._client.delete_messages( await self.get_input_chat(), [self.query.msg_id], *args, **kwargs )
class CallbackQuery(EventBuilder): ''' Occurs whenever you sign in as a bot and a user clicks one of the inline buttons on your messages. Note that the `chats` parameter will **not** work with normal IDs or peers if the clicked inline button comes from a "via bot" message. The `chats` parameter also supports checking against the `chat_instance` which should be used for inline callbacks. Args: data (`bytes`, `str`, `callable`, optional): If set, the inline button payload data must match this data. A UTF-8 string can also be given, a regex or a callable. For instance, to check against ``'data_1'`` and ``'data_2'`` you can use ``re.compile(b'data_')``. pattern (`bytes`, `str`, `callable`, `Pattern`, optional): If set, only buttons with payload matching this pattern will be handled. You can specify a regex-like string which will be matched against the payload data, a callable function that returns `True` if a the payload data is acceptable, or a compiled regex pattern. Example .. code-block:: python from telethon import events, Button # Handle all callback queries and check data inside the handler @client.on(events.CallbackQuery) async def handler(event): if event.data == b'yes': await event.answer('Correct answer!') # Handle only callback queries with data being b'no' @client.on(events.CallbackQuery(data=b'no')) async def handler(event): # Pop-up message with alert await event.answer('Wrong answer!', alert=True) # Send a message with buttons users can click async def main(): await client.send_message(user, 'Yes or no?', buttons=[ Button.inline('Yes!', b'yes'), Button.inline('Nope', b'no') ]) ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None, data=None, pattern=None): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass class Event(EventCommon, SenderGetter): ''' Represents the event of a new callback query. Members: query (:tl:`UpdateBotCallbackQuery`): The original :tl:`UpdateBotCallbackQuery`. data_match (`obj`, optional): The object returned by the ``data=`` parameter when creating the event builder, if any. Similar to ``pattern_match`` for the new message event. pattern_match (`obj`, optional): Alias for ``data_match``. ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None, data=None, pattern=None): pass def _set_client(self, client): pass @property def id(self): ''' Returns the query ID. The user clicking the inline button is the one who generated this random ID. ''' pass @property def message_id(self): ''' Returns the message ID to which the clicked inline button belongs. ''' pass @property def data(self): ''' Returns the data payload from the original inline button. ''' pass @property def chat_instance(self): ''' Unique identifier for the chat where the callback occurred. Useful for high scores in games. ''' pass async def get_message(self): ''' Returns the message to which the clicked inline button belongs. ''' pass async def _refetch_sender(self): pass async def answer( self, message=None, cache_time=0, *, url=None, alert=False): ''' Answers the callback query (and stops the loading circle). Args: message (`str`, optional): The toast message to show feedback to the user. cache_time (`int`, optional): For how long this result should be cached on the user's client. Defaults to 0 for no cache. url (`str`, optional): The URL to be opened in the user's client. Note that the only valid URLs are those of games your bot has, or alternatively a 't.me/your_bot?start=xyz' parameter. alert (`bool`, optional): Whether an alert (a pop-up dialog) should be used instead of showing a toast. Defaults to `False`. ''' pass @property def via_inline(self): ''' Whether this callback was generated from an inline button sent via an inline query or not. If the bot sent the message itself with buttons, and one of those is clicked, this will be `False`. If a user sent the message coming from an inline query to the bot, and one of those is clicked, this will be `True`. If it's `True`, it's likely that the bot is **not** in the chat, so methods like `respond` or `delete` won't work (but `edit` will always work). ''' pass async def respond(self, *args, **kwargs): ''' Responds to the message (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. ''' pass async def reply(self, *args, **kwargs): ''' Replies to the message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. ''' pass async def edit(self, *args, **kwargs): ''' Edits the message. Shorthand for `telethon.client.messages.MessageMethods.edit_message` with the ``entity`` set to the correct :tl:`InputBotInlineMessageID` or :tl:`InputBotInlineMessageID64`. Returns `True` if the edit was successful. This method also creates a task to `answer` the callback. .. note:: This method won't respect the previous message unlike `Message.edit <telethon.tl.custom.message.Message.edit>`, since the message object is normally not present. ''' pass async def delete(self, *args, **kwargs): ''' Deletes the message. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. If you need to delete more than one message at once, don't use this `delete` method. Use a `telethon.client.telegramclient.TelegramClient` instance directly. This method also creates a task to `answer` the callback. This method will likely fail if `via_inline` is `True`. ''' pass
25
13
15
2
8
5
3
0.91
1
5
0
0
2
2
3
28
336
57
146
41
119
133
108
33
89
10
5
3
48
146,693
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/messageread.py
telethon.events.messageread.MessageRead
class MessageRead(EventBuilder): """ Occurs whenever one or more messages are read in a chat. Args: inbox (`bool`, optional): If this argument is `True`, then when you read someone else's messages the event will be fired. By default (`False`) only when messages you sent are read by someone else will fire it. Example .. code-block:: python from telethon import events @client.on(events.MessageRead) async def handler(event): # Log when someone reads your messages print('Someone has read all your messages until', event.max_id) @client.on(events.MessageRead(inbox=True)) async def handler(event): # Log when you read message in a chat (from your "inbox") print('You have read messages until', event.max_id) """ def __init__( self, chats=None, *, blacklist_chats=False, func=None, inbox=False): super().__init__(chats, blacklist_chats=blacklist_chats, func=func) self.inbox = inbox @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, types.UpdateReadHistoryInbox): return cls.Event(update.peer, update.max_id, False) elif isinstance(update, types.UpdateReadHistoryOutbox): return cls.Event(update.peer, update.max_id, True) elif isinstance(update, types.UpdateReadChannelInbox): return cls.Event(types.PeerChannel(update.channel_id), update.max_id, False) elif isinstance(update, types.UpdateReadChannelOutbox): return cls.Event(types.PeerChannel(update.channel_id), update.max_id, True) elif isinstance(update, types.UpdateReadMessagesContents): return cls.Event(message_ids=update.messages, contents=True) elif isinstance(update, types.UpdateChannelReadMessagesContents): return cls.Event(types.PeerChannel(update.channel_id), message_ids=update.messages, contents=True) def filter(self, event): if self.inbox == event.outbox: return return super().filter(event) class Event(EventCommon): """ Represents the event of one or more messages being read. Members: max_id (`int`): Up to which message ID has been read. Every message with an ID equal or lower to it have been read. outbox (`bool`): `True` if someone else has read your messages. contents (`bool`): `True` if what was read were the contents of a message. This will be the case when e.g. you play a voice note. It may only be set on ``inbox`` events. """ def __init__(self, peer=None, max_id=None, out=False, contents=False, message_ids=None): self.outbox = out self.contents = contents self._message_ids = message_ids or [] self._messages = None self.max_id = max_id or max(message_ids or [], default=None) super().__init__(peer, self.max_id) @property def inbox(self): """ `True` if you have read someone else's messages. """ return not self.outbox @property def message_ids(self): """ The IDs of the messages **which contents'** were read. Use :meth:`is_read` if you need to check whether a message was read instead checking if it's in here. """ return self._message_ids async def get_messages(self): """ Returns the list of `Message <telethon.tl.custom.message.Message>` **which contents'** were read. Use :meth:`is_read` if you need to check whether a message was read instead checking if it's in here. """ if self._messages is None: chat = await self.get_input_chat() if not chat: self._messages = [] else: self._messages = await self._client.get_messages( chat, ids=self._message_ids) return self._messages def is_read(self, message): """ Returns `True` if the given message (or its ID) has been read. If a list-like argument is provided, this method will return a list of booleans indicating which messages have been read. """ if utils.is_list_like(message): return [(m if isinstance(m, int) else m.id) <= self.max_id for m in message] else: return (message if isinstance(message, int) else message.id) <= self.max_id def __contains__(self, message): """`True` if the message(s) are read message.""" if utils.is_list_like(message): return all(self.is_read(message)) else: return self.is_read(message)
class MessageRead(EventBuilder): ''' Occurs whenever one or more messages are read in a chat. Args: inbox (`bool`, optional): If this argument is `True`, then when you read someone else's messages the event will be fired. By default (`False`) only when messages you sent are read by someone else will fire it. Example .. code-block:: python from telethon import events @client.on(events.MessageRead) async def handler(event): # Log when someone reads your messages print('Someone has read all your messages until', event.max_id) @client.on(events.MessageRead(inbox=True)) async def handler(event): # Log when you read message in a chat (from your "inbox") print('You have read messages until', event.max_id) ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None, inbox=False): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass class Event(EventCommon): ''' Represents the event of one or more messages being read. Members: max_id (`int`): Up to which message ID has been read. Every message with an ID equal or lower to it have been read. outbox (`bool`): `True` if someone else has read your messages. contents (`bool`): `True` if what was read were the contents of a message. This will be the case when e.g. you play a voice note. It may only be set on ``inbox`` events. ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None, inbox=False): pass @property def inbox(self): ''' `True` if you have read someone else's messages. ''' pass @property def message_ids(self): ''' The IDs of the messages **which contents'** were read. Use :meth:`is_read` if you need to check whether a message was read instead checking if it's in here. ''' pass async def get_messages(self): ''' Returns the list of `Message <telethon.tl.custom.message.Message>` **which contents'** were read. Use :meth:`is_read` if you need to check whether a message was read instead checking if it's in here. ''' pass def is_read(self, message): ''' Returns `True` if the given message (or its ID) has been read. If a list-like argument is provided, this method will return a list of booleans indicating which messages have been read. ''' pass def __contains__(self, message): '''`True` if the message(s) are read message.''' pass
14
7
9
1
7
2
2
0.81
1
1
0
0
2
1
3
28
137
21
64
23
48
52
43
18
32
7
5
2
22
146,694
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.UnauthorizedError
class UnauthorizedError(RPCError): """ There was an unauthorized attempt to use functionality available only to authorized users. """ code = 401 message = 'UNAUTHORIZED'
class UnauthorizedError(RPCError): ''' There was an unauthorized attempt to use functionality available only to authorized users. ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
13
7
0
3
3
2
4
3
3
2
0
4
0
0
146,695
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/__init__.py
telethon.events.StopPropagation
class StopPropagation(Exception): """ If this exception is raised in any of the handlers for a given event, it will stop the execution of all other registered event handlers. It can be seen as the ``StopIteration`` in a for loop but for events. Example usage: >>> from telethon import TelegramClient, events >>> client = TelegramClient(...) >>> >>> @client.on(events.NewMessage) ... async def delete(event): ... await event.delete() ... # No other event handler will have a chance to handle this event ... raise StopPropagation ... >>> @client.on(events.NewMessage) ... async def _(event): ... # Will never be reached, because it is the second handler ... pass """ # For some reason Sphinx wants the silly >>> or # it will show warnings and look bad when generated. pass
class StopPropagation(Exception): ''' If this exception is raised in any of the handlers for a given event, it will stop the execution of all other registered event handlers. It can be seen as the ``StopIteration`` in a for loop but for events. Example usage: >>> from telethon import TelegramClient, events >>> client = TelegramClient(...) >>> >>> @client.on(events.NewMessage) ... async def delete(event): ... await event.delete() ... # No other event handler will have a chance to handle this event ... raise StopPropagation ... >>> @client.on(events.NewMessage) ... async def _(event): ... # Will never be reached, because it is the second handler ... pass '''
1
1
0
0
0
0
0
10.5
1
0
0
0
0
0
0
10
25
2
2
1
1
21
2
1
1
0
3
0
0
146,696
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/userupdate.py
telethon.events.userupdate.UserUpdate
class UserUpdate(EventBuilder): """ Occurs whenever a user goes online, starts typing, etc. Example .. code-block:: python from telethon import events @client.on(events.UserUpdate) async def handler(event): # If someone is uploading, say something if event.uploading: await client.send_message(event.user_id, 'What are you sending?') """ @classmethod def build(cls, update, others=None, self_id=None): if isinstance(update, types.UpdateUserStatus): return cls.Event(types.PeerUser(update.user_id), status=update.status) elif isinstance(update, types.UpdateChannelUserTyping): return cls.Event(update.from_id, chat_peer=types.PeerChannel(update.channel_id), typing=update.action) elif isinstance(update, types.UpdateChatUserTyping): return cls.Event(update.from_id, chat_peer=types.PeerChat(update.chat_id), typing=update.action) elif isinstance(update, types.UpdateUserTyping): return cls.Event(update.user_id, typing=update.action) class Event(EventCommon, SenderGetter): """ Represents the event of a user update such as gone online, started typing, etc. Members: status (:tl:`UserStatus`, optional): The user status if the update is about going online or offline. You should check this attribute first before checking any of the seen within properties, since they will all be `None` if the status is not set. action (:tl:`SendMessageAction`, optional): The "typing" action if any the user is performing if any. You should check this attribute first before checking any of the typing properties, since they will all be `None` if the action is not set. """ def __init__(self, peer, *, status=None, chat_peer=None, typing=None): super().__init__(chat_peer or peer) SenderGetter.__init__(self, utils.get_peer_id(peer)) self.status = status self.action = typing def _set_client(self, client): super()._set_client(client) self._sender, self._input_sender = utils._get_entity_pair( self.sender_id, self._entities, client._mb_entity_cache) @property def user(self): """Alias for `sender <telethon.tl.custom.sendergetter.SenderGetter.sender>`.""" return self.sender async def get_user(self): """Alias for `get_sender <telethon.tl.custom.sendergetter.SenderGetter.get_sender>`.""" return await self.get_sender() @property def input_user(self): """Alias for `input_sender <telethon.tl.custom.sendergetter.SenderGetter.input_sender>`.""" return self.input_sender async def get_input_user(self): """Alias for `get_input_sender <telethon.tl.custom.sendergetter.SenderGetter.get_input_sender>`.""" return await self.get_input_sender() @property def user_id(self): """Alias for `sender_id <telethon.tl.custom.sendergetter.SenderGetter.sender_id>`.""" return self.sender_id @property @_requires_action def typing(self): """ `True` if the action is typing a message. """ return isinstance(self.action, types.SendMessageTypingAction) @property @_requires_action def uploading(self): """ `True` if the action is uploading something. """ return isinstance(self.action, ( types.SendMessageChooseContactAction, types.SendMessageChooseStickerAction, types.SendMessageUploadAudioAction, types.SendMessageUploadDocumentAction, types.SendMessageUploadPhotoAction, types.SendMessageUploadRoundAction, types.SendMessageUploadVideoAction )) @property @_requires_action def recording(self): """ `True` if the action is recording something. """ return isinstance(self.action, ( types.SendMessageRecordAudioAction, types.SendMessageRecordRoundAction, types.SendMessageRecordVideoAction )) @property @_requires_action def playing(self): """ `True` if the action is playing a game. """ return isinstance(self.action, types.SendMessageGamePlayAction) @property @_requires_action def cancel(self): """ `True` if the action was cancelling other actions. """ return isinstance(self.action, types.SendMessageCancelAction) @property @_requires_action def geo(self): """ `True` if what's being uploaded is a geo. """ return isinstance(self.action, types.SendMessageGeoLocationAction) @property @_requires_action def audio(self): """ `True` if what's being recorded/uploaded is an audio. """ return isinstance(self.action, ( types.SendMessageRecordAudioAction, types.SendMessageUploadAudioAction )) @property @_requires_action def round(self): """ `True` if what's being recorded/uploaded is a round video. """ return isinstance(self.action, ( types.SendMessageRecordRoundAction, types.SendMessageUploadRoundAction )) @property @_requires_action def video(self): """ `True` if what's being recorded/uploaded is an video. """ return isinstance(self.action, ( types.SendMessageRecordVideoAction, types.SendMessageUploadVideoAction )) @property @_requires_action def contact(self): """ `True` if what's being uploaded (selected) is a contact. """ return isinstance(self.action, types.SendMessageChooseContactAction) @property @_requires_action def document(self): """ `True` if what's being uploaded is document. """ return isinstance(self.action, types.SendMessageUploadDocumentAction) @property @_requires_action def sticker(self): """ `True` if what's being uploaded is a sticker. """ return isinstance(self.action, types.SendMessageChooseStickerAction) @property @_requires_action def photo(self): """ `True` if what's being uploaded is a photo. """ return isinstance(self.action, types.SendMessageUploadPhotoAction) @property @_requires_status def last_seen(self): """ Exact `datetime.datetime` when the user was last seen if known. """ if isinstance(self.status, types.UserStatusOffline): return self.status.was_online @property @_requires_status def until(self): """ The `datetime.datetime` until when the user should appear online. """ if isinstance(self.status, types.UserStatusOnline): return self.status.expires def _last_seen_delta(self): if isinstance(self.status, types.UserStatusOffline): return datetime.datetime.now(tz=datetime.timezone.utc) - self.status.was_online elif isinstance(self.status, types.UserStatusOnline): return datetime.timedelta(days=0) elif isinstance(self.status, types.UserStatusRecently): return datetime.timedelta(days=1) elif isinstance(self.status, types.UserStatusLastWeek): return datetime.timedelta(days=7) elif isinstance(self.status, types.UserStatusLastMonth): return datetime.timedelta(days=30) else: return datetime.timedelta(days=365) @property @_requires_status def online(self): """ `True` if the user is currently online, """ return self._last_seen_delta() <= datetime.timedelta(days=0) @property @_requires_status def recently(self): """ `True` if the user was seen within a day. """ return self._last_seen_delta() <= datetime.timedelta(days=1) @property @_requires_status def within_weeks(self): """ `True` if the user was seen within 7 days. """ return self._last_seen_delta() <= datetime.timedelta(days=7) @property @_requires_status def within_months(self): """ `True` if the user was seen within 30 days. """ return self._last_seen_delta() <= datetime.timedelta(days=30)
class UserUpdate(EventBuilder): ''' Occurs whenever a user goes online, starts typing, etc. Example .. code-block:: python from telethon import events @client.on(events.UserUpdate) async def handler(event): # If someone is uploading, say something if event.uploading: await client.send_message(event.user_id, 'What are you sending?') ''' @classmethod def build(cls, update, others=None, self_id=None): pass class Event(EventCommon, SenderGetter): ''' Represents the event of a user update such as gone online, started typing, etc. Members: status (:tl:`UserStatus`, optional): The user status if the update is about going online or offline. You should check this attribute first before checking any of the seen within properties, since they will all be `None` if the status is not set. action (:tl:`SendMessageAction`, optional): The "typing" action if any the user is performing if any. You should check this attribute first before checking any of the typing properties, since they will all be `None` if the action is not set. ''' def __init__(self, peer, *, status=None, chat_peer=None, typing=None): pass def _set_client(self, client): pass @property def user(self): '''Alias for `sender <telethon.tl.custom.sendergetter.SenderGetter.sender>`.''' pass async def get_user(self): '''Alias for `get_sender <telethon.tl.custom.sendergetter.SenderGetter.get_sender>`.''' pass @property def input_user(self): '''Alias for `input_sender <telethon.tl.custom.sendergetter.SenderGetter.input_sender>`.''' pass async def get_input_user(self): '''Alias for `get_input_sender <telethon.tl.custom.sendergetter.SenderGetter.get_input_sender>`.''' pass @property def user_id(self): '''Alias for `sender_id <telethon.tl.custom.sendergetter.SenderGetter.sender_id>`.''' pass @property @_requires_action def typing(self): ''' `True` if the action is typing a message. ''' pass @property @_requires_action def uploading(self): ''' `True` if the action is uploading something. ''' pass @property @_requires_action def recording(self): ''' `True` if the action is recording something. ''' pass @property @_requires_action def playing(self): ''' `True` if the action is playing a game. ''' pass @property @_requires_action def cancel(self): ''' `True` if the action was cancelling other actions. ''' pass @property @_requires_action def geo(self): ''' `True` if what's being uploaded is a geo. ''' pass @property @_requires_action def audio(self): ''' `True` if what's being recorded/uploaded is an audio. ''' pass @property @_requires_action def round(self): ''' `True` if what's being recorded/uploaded is a round video. ''' pass @property @_requires_action def video(self): ''' `True` if what's being recorded/uploaded is an video. ''' pass @property @_requires_action def contact(self): ''' `True` if what's being uploaded (selected) is a contact. ''' pass @property @_requires_action def document(self): ''' `True` if what's being uploaded is document. ''' pass @property @_requires_action def sticker(self): ''' `True` if what's being uploaded is a sticker. ''' pass @property @_requires_action def photo(self): ''' `True` if what's being uploaded is a photo. ''' pass @property @_requires_status def last_seen(self): ''' Exact `datetime.datetime` when the user was last seen if known. ''' pass @property @_requires_status def until(self): ''' The `datetime.datetime` until when the user should appear online. ''' pass def _last_seen_delta(self): pass @property @_requires_status def online(self): ''' `True` if the user is currently online, ''' pass @property @_requires_status def recently(self): ''' `True` if the user was seen within a day. ''' pass @property @_requires_status def within_weeks(self): ''' `True` if the user was seen within 7 days. ''' pass @property @_requires_status def within_months(self): ''' `True` if the user was seen within 30 days. ''' pass
72
26
6
0
4
2
1
0.58
1
0
0
0
0
0
1
26
275
35
152
56
80
88
74
33
44
6
5
1
39
146,697
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.TimedOutError
class TimedOutError(RPCError): """ Clicking the inline buttons of bots that never (or take to long to) call ``answerCallbackQuery`` will result in this "special" RPCError. """ code = 503 # Only witnessed as -503 message = 'Timeout'
class TimedOutError(RPCError): ''' Clicking the inline buttons of bots that never (or take to long to) call ``answerCallbackQuery`` will result in this "special" RPCError. ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
13
7
0
3
3
2
5
3
3
2
0
4
0
0
146,698
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.ServerError
class ServerError(RPCError): """ An internal server error occurred while a request was being processed for example, there was a disruption while accessing a database or file storage. """ code = 500 # Also witnessed as -500 message = 'INTERNAL'
class ServerError(RPCError): ''' An internal server error occurred while a request was being processed for example, there was a disruption while accessing a database or file storage. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
13
8
0
3
3
2
6
3
3
2
0
4
0
0
146,699
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.RPCError
class RPCError(Exception): """Base class for all Remote Procedure Call errors.""" code = None message = None def __init__(self, request, message, code=None): super().__init__('RPCError {}: {}{}'.format( code or self.code, message, self._fmt_request(request))) self.request = request self.code = code self.message = message @staticmethod def _fmt_request(request): n = 0 reason = '' while isinstance(request, _NESTS_QUERY): n += 1 reason += request.__class__.__name__ + '(' request = request.query reason += request.__class__.__name__ + ')' * n return ' (caused by {})'.format(reason) def __reduce__(self): return type(self), (self.request, self.message, self.code)
class RPCError(Exception): '''Base class for all Remote Procedure Call errors.''' def __init__(self, request, message, code=None): pass @staticmethod def _fmt_request(request): pass def __reduce__(self): pass
5
1
6
1
6
0
1
0.05
1
2
0
9
2
1
3
13
27
5
21
10
16
1
19
9
15
2
3
1
4
146,700
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.NotFoundError
class NotFoundError(RPCError): """ An attempt to invoke a non-existent object, such as a method. """ code = 404 message = 'NOT_FOUND'
class NotFoundError(RPCError): ''' An attempt to invoke a non-existent object, such as a method. ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
13
6
0
3
3
2
3
3
3
2
0
4
0
0
146,701
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.InvalidDCError
class InvalidDCError(RPCError): """ The request must be repeated, but directed to a different data center. """ code = 303 message = 'ERROR_SEE_OTHER'
class InvalidDCError(RPCError): ''' The request must be repeated, but directed to a different data center. ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
13
6
0
3
3
2
3
3
3
2
0
4
0
0
146,702
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.ForbiddenError
class ForbiddenError(RPCError): """ Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user. """ code = 403 message = 'FORBIDDEN'
class ForbiddenError(RPCError): ''' Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user. ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
13
7
0
3
3
2
4
3
3
2
0
4
0
0
146,703
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.FloodError
class FloodError(RPCError): """ The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number. """ code = 420 message = 'FLOOD'
class FloodError(RPCError): ''' The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
13
9
0
3
3
2
6
3
3
2
0
4
0
0
146,704
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.BadRequestError
class BadRequestError(RPCError): """ The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated. """ code = 400 message = 'BAD_REQUEST'
class BadRequestError(RPCError): ''' The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated. ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
13
8
0
3
3
2
5
3
3
2
0
4
0
0
146,705
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/rpcbaseerrors.py
telethon.errors.rpcbaseerrors.AuthKeyError
class AuthKeyError(RPCError): """ Errors related to invalid authorization key, like AUTH_KEY_DUPLICATED which can cause the connection to fail. """ code = 406 message = 'AUTH_KEY'
class AuthKeyError(RPCError): ''' Errors related to invalid authorization key, like AUTH_KEY_DUPLICATED which can cause the connection to fail. ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
13
7
0
3
3
2
4
3
3
2
0
4
0
0
146,706
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/common.py
telethon.errors.common.TypeNotFoundError
class TypeNotFoundError(Exception): """ Occurs when a type is not found, for example, when trying to read a TLObject with an invalid constructor code. """ def __init__(self, invalid_constructor_id, remaining): super().__init__( 'Could not find a matching Constructor ID for the TLObject ' 'that was supposed to be read with ID {:08x}. See the FAQ ' 'for more details. ' 'Remaining bytes: {!r}'.format(invalid_constructor_id, remaining)) self.invalid_constructor_id = invalid_constructor_id self.remaining = remaining
class TypeNotFoundError(Exception): ''' Occurs when a type is not found, for example, when trying to read a TLObject with an invalid constructor code. ''' def __init__(self, invalid_constructor_id, remaining): pass
2
1
9
1
8
0
1
0.44
1
1
0
0
1
2
1
11
14
1
9
4
7
4
5
4
3
1
3
0
1
146,707
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/common.py
telethon.errors.common.SecurityError
class SecurityError(Exception): """ Generic security error, mostly used when generating a new AuthKey. """ def __init__(self, *args): if not args: args = ['A security check failed.'] super().__init__(*args)
class SecurityError(Exception): ''' Generic security error, mostly used when generating a new AuthKey. ''' def __init__(self, *args): pass
2
1
4
0
4
0
2
0.6
1
1
0
1
1
0
1
11
8
0
5
2
3
3
5
2
3
2
3
1
2
146,708
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/events/album.py
telethon.events.album.Album
class Album(EventBuilder): """ Occurs whenever you receive an album. This event only exists to ease dealing with an unknown amount of messages that belong to the same album. Example .. code-block:: python from telethon import events @client.on(events.Album) async def handler(event): # Counting how many photos or videos the album has print('Got an album with', len(event), 'items') # Forwarding the album as a whole to some chat event.forward_to(chat) # Printing the caption print(event.text) # Replying to the fifth item in the album await event.messages[4].reply('Cool!') """ def __init__( self, chats=None, *, blacklist_chats=False, func=None): super().__init__(chats, blacklist_chats=blacklist_chats, func=func) @classmethod def build(cls, update, others=None, self_id=None): # TODO normally we'd only check updates if they come with other updates # but MessageBox is not designed for this so others will always be None. # In essence we always rely on AlbumHack rather than returning early if not others. others = [update] if isinstance(update, (types.UpdateNewMessage, types.UpdateNewChannelMessage)): if not isinstance(update.message, types.Message): return # We don't care about MessageService's here group = update.message.grouped_id if group is None: return # It must be grouped # Check whether we are supposed to skip this update, and # if we do also remove it from the ignore list since we # won't need to check against it again. if _IGNORE_DICT.pop(id(update), None): return # Check if the ignore list is too big, and if it is clean it # TODO time could technically go backwards; time is not monotonic now = time.time() if len(_IGNORE_DICT) > _IGNORE_MAX_SIZE: for i in [i for i, t in _IGNORE_DICT.items() if now - t > _IGNORE_MAX_AGE]: del _IGNORE_DICT[i] # Add the other updates to the ignore list for u in others: if u is not update: _IGNORE_DICT[id(u)] = now # Figure out which updates share the same group and use those return cls.Event([ u.message for u in others if (isinstance(u, (types.UpdateNewMessage, types.UpdateNewChannelMessage)) and isinstance(u.message, types.Message) and u.message.grouped_id == group) ]) def filter(self, event): # Albums with less than two messages require a few hacks to work. if len(event.messages) > 1: return super().filter(event) class Event(EventCommon, SenderGetter): """ Represents the event of a new album. Members: messages (Sequence[`Message <telethon.tl.custom.message.Message>`]): The list of messages belonging to the same album. """ def __init__(self, messages): message = messages[0] super().__init__(chat_peer=message.peer_id, msg_id=message.id, broadcast=bool(message.post)) SenderGetter.__init__(self, message.sender_id) self.messages = messages def _set_client(self, client): super()._set_client(client) self._sender, self._input_sender = utils._get_entity_pair( self.sender_id, self._entities, client._mb_entity_cache) for msg in self.messages: msg._finish_init(client, self._entities, None) if len(self.messages) == 1: # This will require hacks to be a proper album event hack = client._albums.get(self.grouped_id) if hack is None: client._albums[self.grouped_id] = AlbumHack(client, self) else: hack.extend(self.messages) @property def grouped_id(self): """ The shared ``grouped_id`` between all the messages. """ return self.messages[0].grouped_id @property def text(self): """ The message text of the first photo with a caption, formatted using the client's default parse mode. """ return next((m.text for m in self.messages if m.text), '') @property def raw_text(self): """ The raw message text of the first photo with a caption, ignoring any formatting. """ return next((m.raw_text for m in self.messages if m.raw_text), '') @property def is_reply(self): """ `True` if the album is a reply to some other message. Remember that you can access the ID of the message this one is replying to through `reply_to_msg_id`, and the `Message` object with `get_reply_message()`. """ # Each individual message in an album all reply to the same message return self.messages[0].is_reply @property def forward(self): """ The `Forward <telethon.tl.custom.forward.Forward>` information for the first message in the album if it was forwarded. """ # Each individual message in an album all reply to the same message return self.messages[0].forward # endregion Public Properties # region Public Methods async def get_reply_message(self): """ The `Message <telethon.tl.custom.message.Message>` that this album is replying to, or `None`. The result will be cached after its first use. """ return await self.messages[0].get_reply_message() async def respond(self, *args, **kwargs): """ Responds to the album (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. """ return await self.messages[0].respond(*args, **kwargs) async def reply(self, *args, **kwargs): """ Replies to the first photo in the album (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. """ return await self.messages[0].reply(*args, **kwargs) async def forward_to(self, *args, **kwargs): """ Forwards the entire album. Shorthand for `telethon.client.messages.MessageMethods.forward_messages` with both ``messages`` and ``from_peer`` already set. """ if self._client: kwargs['messages'] = self.messages kwargs['from_peer'] = await self.get_input_chat() return await self._client.forward_messages(*args, **kwargs) async def edit(self, *args, **kwargs): """ Edits the first caption or the message, or the first messages' caption if no caption is set, iff it's outgoing. Shorthand for `telethon.client.messages.MessageMethods.edit_message` with both ``entity`` and ``message`` already set. Returns `None` if the message was incoming, or the edited `Message` otherwise. .. note:: This is different from `client.edit_message <telethon.client.messages.MessageMethods.edit_message>` and **will respect** the previous state of the message. For example, if the message didn't have a link preview, the edit won't add one by default, and you should force it by setting it to `True` if you want it. This is generally the most desired and convenient behaviour, and will work for link previews and message buttons. """ for msg in self.messages: if msg.raw_text: return await msg.edit(*args, **kwargs) return await self.messages[0].edit(*args, **kwargs) async def delete(self, *args, **kwargs): """ Deletes the entire album. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. """ if self._client: return await self._client.delete_messages( await self.get_input_chat(), self.messages, *args, **kwargs ) async def mark_read(self): """ Marks the entire album as read. Shorthand for `client.send_read_acknowledge() <telethon.client.messages.MessageMethods.send_read_acknowledge>` with both ``entity`` and ``message`` already set. """ if self._client: await self._client.send_read_acknowledge( await self.get_input_chat(), max_id=self.messages[-1].id) async def pin(self, *, notify=False): """ Pins the first photo in the album. Shorthand for `telethon.client.messages.MessageMethods.pin_message` with both ``entity`` and ``message`` already set. """ return await self.messages[0].pin(notify=notify) def __len__(self): """ Return the amount of messages in the album. Equivalent to ``len(self.messages)``. """ return len(self.messages) def __iter__(self): """ Iterate over the messages in the album. Equivalent to ``iter(self.messages)``. """ return iter(self.messages) def __getitem__(self, n): """ Access the n'th message in the album. Equivalent to ``event.messages[n]``. """ return self.messages[n]
class Album(EventBuilder): ''' Occurs whenever you receive an album. This event only exists to ease dealing with an unknown amount of messages that belong to the same album. Example .. code-block:: python from telethon import events @client.on(events.Album) async def handler(event): # Counting how many photos or videos the album has print('Got an album with', len(event), 'items') # Forwarding the album as a whole to some chat event.forward_to(chat) # Printing the caption print(event.text) # Replying to the fifth item in the album await event.messages[4].reply('Cool!') ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None): pass @classmethod def build(cls, update, others=None, self_id=None): pass def filter(self, event): pass class Event(EventCommon, SenderGetter): ''' Represents the event of a new album. Members: messages (Sequence[`Message <telethon.tl.custom.message.Message>`]): The list of messages belonging to the same album. ''' def __init__( self, chats=None, *, blacklist_chats=False, func=None): pass def _set_client(self, client): pass @property def grouped_id(self): ''' The shared ``grouped_id`` between all the messages. ''' pass @property def text(self): ''' The message text of the first photo with a caption, formatted using the client's default parse mode. ''' pass @property def raw_text(self): ''' The raw message text of the first photo with a caption, ignoring any formatting. ''' pass @property def is_reply(self): ''' `True` if the album is a reply to some other message. Remember that you can access the ID of the message this one is replying to through `reply_to_msg_id`, and the `Message` object with `get_reply_message()`. ''' pass @property def forward(self): ''' The `Forward <telethon.tl.custom.forward.Forward>` information for the first message in the album if it was forwarded. ''' pass async def get_reply_message(self): ''' The `Message <telethon.tl.custom.message.Message>` that this album is replying to, or `None`. The result will be cached after its first use. ''' pass async def respond(self, *args, **kwargs): ''' Responds to the album (not as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. ''' pass async def reply(self, *args, **kwargs): ''' Replies to the first photo in the album (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. ''' pass async def forward_to(self, *args, **kwargs): ''' Forwards the entire album. Shorthand for `telethon.client.messages.MessageMethods.forward_messages` with both ``messages`` and ``from_peer`` already set. ''' pass async def edit(self, *args, **kwargs): ''' Edits the first caption or the message, or the first messages' caption if no caption is set, iff it's outgoing. Shorthand for `telethon.client.messages.MessageMethods.edit_message` with both ``entity`` and ``message`` already set. Returns `None` if the message was incoming, or the edited `Message` otherwise. .. note:: This is different from `client.edit_message <telethon.client.messages.MessageMethods.edit_message>` and **will respect** the previous state of the message. For example, if the message didn't have a link preview, the edit won't add one by default, and you should force it by setting it to `True` if you want it. This is generally the most desired and convenient behaviour, and will work for link previews and message buttons. ''' pass async def delete(self, *args, **kwargs): ''' Deletes the entire album. You're responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for `telethon.client.messages.MessageMethods.delete_messages` with ``entity`` and ``message_ids`` already set. ''' pass async def mark_read(self): ''' Marks the entire album as read. Shorthand for `client.send_read_acknowledge() <telethon.client.messages.MessageMethods.send_read_acknowledge>` with both ``entity`` and ``message`` already set. ''' pass async def pin(self, *, notify=False): ''' Pins the first photo in the album. Shorthand for `telethon.client.messages.MessageMethods.pin_message` with both ``entity`` and ``message`` already set. ''' pass def __len__(self): ''' Return the amount of messages in the album. Equivalent to ``len(self.messages)``. ''' pass def __iter__(self): ''' Iterate over the messages in the album. Equivalent to ``iter(self.messages)``. ''' pass def __getitem__(self, n): ''' Access the n'th message in the album. Equivalent to ``event.messages[n]``. ''' pass
29
18
10
1
4
5
2
1.3
1
1
0
0
2
0
3
28
276
48
100
40
70
130
80
33
57
9
5
3
38
146,709
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/extensions/binaryreader.py
telethon.extensions.binaryreader.BinaryReader
class BinaryReader: """ Small utility class to read binary data. """ def __init__(self, data): self.stream = BytesIO(data) self._last = None # Should come in handy to spot -404 errors # region Reading # "All numbers are written as little endian." # https://core.telegram.org/mtproto def read_byte(self): """Reads a single byte value.""" return self.read(1)[0] def read_int(self, signed=True): """Reads an integer (4 bytes) value.""" return int.from_bytes(self.read(4), byteorder='little', signed=signed) def read_long(self, signed=True): """Reads a long integer (8 bytes) value.""" return int.from_bytes(self.read(8), byteorder='little', signed=signed) def read_float(self): """Reads a real floating point (4 bytes) value.""" return unpack('<f', self.read(4))[0] def read_double(self): """Reads a real floating point (8 bytes) value.""" return unpack('<d', self.read(8))[0] def read_large_int(self, bits, signed=True): """Reads a n-bits long integer value.""" return int.from_bytes( self.read(bits // 8), byteorder='little', signed=signed) def read(self, length=-1): """Read the given amount of bytes, or -1 to read all remaining.""" result = self.stream.read(length) if (length >= 0) and (len(result) != length): raise BufferError( 'No more data left to read (need {}, got {}: {}); last read {}' .format(length, len(result), repr(result), repr(self._last)) ) self._last = result return result def get_bytes(self): """Gets the byte array representing the current buffer as a whole.""" return self.stream.getvalue() # endregion # region Telegram custom reading def tgread_bytes(self): """ Reads a Telegram-encoded byte array, without the need of specifying its length. """ first_byte = self.read_byte() if first_byte == 254: length = self.read_byte() | (self.read_byte() << 8) | ( self.read_byte() << 16) padding = length % 4 else: length = first_byte padding = (length + 1) % 4 data = self.read(length) if padding > 0: padding = 4 - padding self.read(padding) return data def tgread_string(self): """Reads a Telegram-encoded string.""" return str(self.tgread_bytes(), encoding='utf-8', errors='replace') def tgread_bool(self): """Reads a Telegram boolean value.""" value = self.read_int(signed=False) if value == 0x997275b5: # boolTrue return True elif value == 0xbc799737: # boolFalse return False else: raise RuntimeError('Invalid boolean code {}'.format(hex(value))) def tgread_date(self): """Reads and converts Unix time (used by Telegram) into a Python datetime object. """ value = self.read_int() return _EPOCH + timedelta(seconds=value) def tgread_object(self): """Reads a Telegram object.""" constructor_id = self.read_int(signed=False) clazz = tlobjects.get(constructor_id, None) if clazz is None: # The class was None, but there's still a # chance of it being a manually parsed value like bool! value = constructor_id if value == 0x997275b5: # boolTrue return True elif value == 0xbc799737: # boolFalse return False elif value == 0x1cb5c415: # Vector return [self.tgread_object() for _ in range(self.read_int())] clazz = core_objects.get(constructor_id, None) if clazz is None: # If there was still no luck, give up self.seek(-4) # Go back pos = self.tell_position() error = TypeNotFoundError(constructor_id, self.read()) self.set_position(pos) raise error return clazz.from_reader(self) def tgread_vector(self): """Reads a vector (a list) of Telegram objects.""" if 0x1cb5c415 != self.read_int(signed=False): raise RuntimeError('Invalid constructor code, vector was expected') count = self.read_int() return [self.tgread_object() for _ in range(count)] # endregion def close(self): """Closes the reader, freeing the BytesIO stream.""" self.stream.close() # region Position related def tell_position(self): """Tells the current position on the stream.""" return self.stream.tell() def set_position(self, position): """Sets the current position on the stream.""" self.stream.seek(position) def seek(self, offset): """ Seeks the stream position given an offset from the current position. The offset may be negative. """ self.stream.seek(offset, os.SEEK_CUR) # endregion # region with block def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
class BinaryReader: ''' Small utility class to read binary data. ''' def __init__(self, data): pass def read_byte(self): '''Reads a single byte value.''' pass def read_int(self, signed=True): '''Reads an integer (4 bytes) value.''' pass def read_long(self, signed=True): '''Reads a long integer (8 bytes) value.''' pass def read_float(self): '''Reads a real floating point (4 bytes) value.''' pass def read_double(self): '''Reads a real floating point (8 bytes) value.''' pass def read_large_int(self, bits, signed=True): '''Reads a n-bits long integer value.''' pass def read_byte(self): '''Read the given amount of bytes, or -1 to read all remaining.''' pass def get_bytes(self): '''Gets the byte array representing the current buffer as a whole.''' pass def tgread_bytes(self): ''' Reads a Telegram-encoded byte array, without the need of specifying its length. ''' pass def tgread_string(self): '''Reads a Telegram-encoded string.''' pass def tgread_bool(self): '''Reads a Telegram boolean value.''' pass def tgread_date(self): '''Reads and converts Unix time (used by Telegram) into a Python datetime object. ''' pass def tgread_object(self): '''Reads a Telegram object.''' pass def tgread_vector(self): '''Reads a vector (a list) of Telegram objects.''' pass def close(self): '''Closes the reader, freeing the BytesIO stream.''' pass def tell_position(self): '''Tells the current position on the stream.''' pass def set_position(self, position): '''Sets the current position on the stream.''' pass def seek(self, offset): ''' Seeks the stream position given an offset from the current position. The offset may be negative. ''' pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass
22
19
6
0
4
2
2
0.53
0
7
1
0
21
2
21
21
166
34
91
39
69
48
81
37
59
6
0
2
32
146,710
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpmtproxy.py
telethon.network.connection.tcpmtproxy.MTProxyIO
class MTProxyIO: """ It's very similar to tcpobfuscated.ObfuscatedIO, but the way encryption keys, protocol tag and dc_id are encoded is different. """ header = None def __init__(self, connection): self._reader = connection._reader self._writer = connection._writer (self.header, self._encrypt, self._decrypt) = self.init_header( connection._secret, connection._dc_id, connection.packet_codec) @staticmethod def init_header(secret, dc_id, packet_codec): # Validate is_dd = (len(secret) == 17) and (secret[0] == 0xDD) is_rand_codec = issubclass( packet_codec, RandomizedIntermediatePacketCodec) if is_dd and not is_rand_codec: raise ValueError( "Only RandomizedIntermediate can be used with dd-secrets") secret = secret[1:] if is_dd else secret if len(secret) != 16: raise ValueError( "MTProxy secret must be a hex-string representing 16 bytes") # Obfuscated messages secrets cannot start with any of these keywords = (b'PVrG', b'GET ', b'POST', b'\xee\xee\xee\xee') while True: random = os.urandom(64) if (random[0] != 0xef and random[:4] not in keywords and random[4:4] != b'\0\0\0\0'): break random = bytearray(random) random_reversed = random[55:7:-1] # Reversed (8, len=48) # Encryption has "continuous buffer" enabled encrypt_key = hashlib.sha256( bytes(random[8:40]) + secret).digest() encrypt_iv = bytes(random[40:56]) decrypt_key = hashlib.sha256( bytes(random_reversed[:32]) + secret).digest() decrypt_iv = bytes(random_reversed[32:48]) encryptor = AESModeCTR(encrypt_key, encrypt_iv) decryptor = AESModeCTR(decrypt_key, decrypt_iv) random[56:60] = packet_codec.obfuscate_tag dc_id_bytes = dc_id.to_bytes(2, "little", signed=True) random = random[:60] + dc_id_bytes + random[62:] random[56:64] = encryptor.encrypt(bytes(random))[56:64] return (random, encryptor, decryptor) async def readexactly(self, n): return self._decrypt.encrypt(await self._reader.readexactly(n)) def write(self, data): self._writer.write(self._encrypt.encrypt(data))
class MTProxyIO: ''' It's very similar to tcpobfuscated.ObfuscatedIO, but the way encryption keys, protocol tag and dc_id are encoded is different. ''' def __init__(self, connection): pass @staticmethod def init_header(secret, dc_id, packet_codec): pass async def readexactly(self, n): pass def write(self, data): pass
6
1
14
2
11
1
2
0.17
0
5
2
0
3
4
4
4
65
11
47
23
41
8
36
21
31
6
0
2
9
146,711
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/extensions/messagepacker.py
telethon.extensions.messagepacker.MessagePacker
class MessagePacker: """ This class packs `RequestState` as outgoing `TLMessages`. The purpose of this class is to support putting N `RequestState` into a queue, and then awaiting for "packed" `TLMessage` in the other end. The simplest case would be ``State -> TLMessage`` (1-to-1 relationship) but for efficiency purposes it's ``States -> Container`` (N-to-1). This addresses several needs: outgoing messages will be smaller, so the encryption and network overhead also is smaller. It's also a central point where outgoing requests are put, and where ready-messages are get. """ def __init__(self, state, loggers): self._state = state self._deque = collections.deque() self._ready = asyncio.Event() self._log = loggers[__name__] def append(self, state): self._deque.append(state) self._ready.set() def extend(self, states): self._deque.extend(states) self._ready.set() async def get(self): """ Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. """ if not self._deque: self._ready.clear() await self._ready.wait() buffer = io.BytesIO() batch = [] size = 0 # Fill a new batch to return while the size is small enough, # as long as we don't exceed the maximum length of messages. while self._deque and len(batch) <= MessageContainer.MAXIMUM_LENGTH: state = self._deque.popleft() size += len(state.data) + TLMessage.SIZE_OVERHEAD if size <= MessageContainer.MAXIMUM_SIZE: state.msg_id = self._state.write_data_as_message( buffer, state.data, isinstance(state.request, TLRequest), after_id=state.after.msg_id if state.after else None ) batch.append(state) self._log.debug('Assigned msg_id = %d to %s (%x)', state.msg_id, state.request.__class__.__name__, id(state.request)) continue if batch: # Put the item back since it can't be sent in this batch self._deque.appendleft(state) break # If a single message exceeds the maximum size, then the # message payload cannot be sent. Telegram would forcibly # close the connection; message would never be confirmed. # # We don't put the item back because it can never be sent. # If we did, we would loop again and reach this same path. # Setting the exception twice results in `InvalidStateError` # and this method should never return with error, which we # really want to avoid. self._log.warning( 'Message payload for %s is too long (%d) and cannot be sent', state.request.__class__.__name__, len(state.data) ) state.future.set_exception( ValueError('Request payload is too big')) size = 0 continue if not batch: return None, None if len(batch) > 1: # Inlined code to pack several messages into a container data = struct.pack( '<Ii', MessageContainer.CONSTRUCTOR_ID, len(batch) ) + buffer.getvalue() buffer = io.BytesIO() container_id = self._state.write_data_as_message( buffer, data, content_related=False ) for s in batch: s.container_id = container_id data = buffer.getvalue() return batch, data
class MessagePacker: ''' This class packs `RequestState` as outgoing `TLMessages`. The purpose of this class is to support putting N `RequestState` into a queue, and then awaiting for "packed" `TLMessage` in the other end. The simplest case would be ``State -> TLMessage`` (1-to-1 relationship) but for efficiency purposes it's ``States -> Container`` (N-to-1). This addresses several needs: outgoing messages will be smaller, so the encryption and network overhead also is smaller. It's also a central point where outgoing requests are put, and where ready-messages are get. ''' def __init__(self, state, loggers): pass def append(self, state): pass def extend(self, states): pass async def get(self): ''' Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. ''' pass
5
2
21
3
14
5
3
0.49
0
4
3
0
4
4
4
4
101
16
57
16
52
28
44
16
39
9
0
2
12
146,712
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpmtproxy.py
telethon.network.connection.tcpmtproxy.ConnectionTcpMTProxyRandomizedIntermediate
class ConnectionTcpMTProxyRandomizedIntermediate(TcpMTProxy): """ Connect to proxy using randomized intermediate protocol (dd-secrets) """ packet_codec = RandomizedIntermediatePacketCodec
class ConnectionTcpMTProxyRandomizedIntermediate(TcpMTProxy): ''' Connect to proxy using randomized intermediate protocol (dd-secrets) ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
42
5
0
2
2
1
3
2
2
1
0
7
0
0
146,713
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpmtproxy.py
telethon.network.connection.tcpmtproxy.ConnectionTcpMTProxyIntermediate
class ConnectionTcpMTProxyIntermediate(TcpMTProxy): """ Connect to proxy using intermediate protocol """ packet_codec = IntermediatePacketCodec
class ConnectionTcpMTProxyIntermediate(TcpMTProxy): ''' Connect to proxy using intermediate protocol ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
42
5
0
2
2
1
3
2
2
1
0
7
0
0
146,714
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpmtproxy.py
telethon.network.connection.tcpmtproxy.ConnectionTcpMTProxyAbridged
class ConnectionTcpMTProxyAbridged(TcpMTProxy): """ Connect to proxy using abridged protocol """ packet_codec = AbridgedPacketCodec
class ConnectionTcpMTProxyAbridged(TcpMTProxy): ''' Connect to proxy using abridged protocol ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
42
5
0
2
2
1
3
2
2
1
0
7
0
0
146,715
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpintermediate.py
telethon.network.connection.tcpintermediate.RandomizedIntermediatePacketCodec
class RandomizedIntermediatePacketCodec(IntermediatePacketCodec): """ Data packets are aligned to 4bytes. This codec adds random bytes of size from 0 to 3 bytes, which are ignored by decoder. """ tag = None obfuscate_tag = b'\xdd\xdd\xdd\xdd' def encode_packet(self, data): pad_size = random.randint(0, 3) padding = os.urandom(pad_size) return super().encode_packet(data + padding) async def read_packet(self, reader): packet_with_padding = await super().read_packet(reader) pad_size = len(packet_with_padding) % 4 if pad_size > 0: return packet_with_padding[:-pad_size] return packet_with_padding
class RandomizedIntermediatePacketCodec(IntermediatePacketCodec): ''' Data packets are aligned to 4bytes. This codec adds random bytes of size from 0 to 3 bytes, which are ignored by decoder. ''' def encode_packet(self, data): pass async def read_packet(self, reader): pass
3
1
5
0
5
0
2
0.31
1
1
0
0
2
0
2
27
19
2
13
9
10
4
13
9
10
2
6
1
3
146,716
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpintermediate.py
telethon.network.connection.tcpintermediate.IntermediatePacketCodec
class IntermediatePacketCodec(PacketCodec): tag = b'\xee\xee\xee\xee' obfuscate_tag = tag def encode_packet(self, data): return struct.pack('<i', len(data)) + data async def read_packet(self, reader): length = struct.unpack('<i', await reader.readexactly(4))[0] return await reader.readexactly(length)
class IntermediatePacketCodec(PacketCodec): def encode_packet(self, data): pass async def read_packet(self, reader): pass
3
0
3
0
3
0
1
0
1
0
0
1
2
0
2
25
10
2
8
6
5
0
8
6
5
1
5
0
2
146,717
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpmtproxy.py
telethon.network.connection.tcpmtproxy.TcpMTProxy
class TcpMTProxy(ObfuscatedConnection): """ Connector which allows user to connect to the Telegram via proxy servers commonly known as MTProxy. Implemented very ugly due to the leaky abstractions in Telethon networking classes that should be refactored later (TODO). .. warning:: The support for TcpMTProxy classes is **EXPERIMENTAL** and prone to be changed. You shouldn't be using this class yet. """ packet_codec = None obfuscated_io = MTProxyIO # noinspection PyUnusedLocal def __init__(self, ip, port, dc_id, *, loggers, proxy=None, local_addr=None): # connect to proxy's host and port instead of telegram's ones proxy_host, proxy_port = self.address_info(proxy) self._secret = self.normalize_secret(proxy[2]) super().__init__( proxy_host, proxy_port, dc_id, loggers=loggers) async def _connect(self, timeout=None, ssl=None): await super()._connect(timeout=timeout, ssl=ssl) # Wait for EOF for 2 seconds (or if _wait_for_data's definition # is missing or different, just sleep for 2 seconds). This way # we give the proxy a chance to close the connection if the current # codec (which the proxy detects with the data we sent) cannot # be used for this proxy. This is a work around for #1134. # TODO Sleeping for N seconds may not be the best solution # TODO This fix could be welcome for HTTP proxies as well try: await asyncio.wait_for(self._reader._wait_for_data('proxy'), 2) except asyncio.TimeoutError: pass except Exception: await asyncio.sleep(2) if self._reader.at_eof(): await self.disconnect() raise ConnectionError( 'Proxy closed the connection after sending initial payload') @staticmethod def address_info(proxy_info): if proxy_info is None: raise ValueError("No proxy info specified for MTProxy connection") return proxy_info[:2] @staticmethod def normalize_secret(secret): if secret[:2] in ("ee", "dd"): # Remove extra bytes secret = secret[2:] try: secret_bytes = bytes.fromhex(secret) except ValueError: secret = secret + '=' * (-len(secret) % 4) secret_bytes = base64.b64decode(secret.encode()) return secret_bytes[:16]
class TcpMTProxy(ObfuscatedConnection): ''' Connector which allows user to connect to the Telegram via proxy servers commonly known as MTProxy. Implemented very ugly due to the leaky abstractions in Telethon networking classes that should be refactored later (TODO). .. warning:: The support for TcpMTProxy classes is **EXPERIMENTAL** and prone to be changed. You shouldn't be using this class yet. ''' def __init__(self, ip, port, dc_id, *, loggers, proxy=None, local_addr=None): pass async def _connect(self, timeout=None, ssl=None): pass @staticmethod def address_info(proxy_info): pass @staticmethod def normalize_secret(secret): pass
7
1
11
1
8
3
3
0.57
1
6
0
3
2
1
4
42
63
10
35
12
28
20
31
10
26
4
6
1
10
146,718
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpintermediate.py
telethon.network.connection.tcpintermediate.ConnectionTcpIntermediate
class ConnectionTcpIntermediate(Connection): """ Intermediate mode between `ConnectionTcpFull` and `ConnectionTcpAbridged`. Always sends 4 extra bytes for the packet length. """ packet_codec = IntermediatePacketCodec
class ConnectionTcpIntermediate(Connection): ''' Intermediate mode between `ConnectionTcpFull` and `ConnectionTcpAbridged`. Always sends 4 extra bytes for the packet length. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
35
6
0
2
2
1
4
2
2
1
0
5
0
0
146,719
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpfull.py
telethon.network.connection.tcpfull.FullPacketCodec
class FullPacketCodec(PacketCodec): tag = None def __init__(self, connection): super().__init__(connection) self._send_counter = 0 # Important or Telegram won't reply def encode_packet(self, data): # https://core.telegram.org/mtproto#tcp-transport # total length, sequence number, packet and checksum (CRC32) length = len(data) + 12 data = struct.pack('<ii', length, self._send_counter) + data crc = struct.pack('<I', crc32(data)) self._send_counter += 1 return data + crc async def read_packet(self, reader): packet_len_seq = await reader.readexactly(8) # 4 and 4 packet_len, seq = struct.unpack('<ii', packet_len_seq) if packet_len < 0 and seq < 0: # It has been observed that the length and seq can be -429, # followed by the body of 4 bytes also being -429. # See https://github.com/LonamiWebs/Telethon/issues/4042. body = await reader.readexactly(4) raise InvalidBufferError(body) elif packet_len < 8: # Currently unknown why packet_len may be less than 8 but not negative. # Attempting to `readexactly` with less than 0 fails without saying what # the number was which is less helpful. raise InvalidBufferError(packet_len_seq) body = await reader.readexactly(packet_len - 8) checksum = struct.unpack('<I', body[-4:])[0] body = body[:-4] valid_checksum = crc32(packet_len_seq + body) if checksum != valid_checksum: raise InvalidChecksumError(checksum, valid_checksum) return body
class FullPacketCodec(PacketCodec): def __init__(self, connection): pass def encode_packet(self, data): pass async def read_packet(self, reader): pass
4
0
12
1
8
3
2
0.38
1
3
2
0
3
1
3
26
40
6
26
13
22
10
25
13
21
4
5
1
6
146,720
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpfull.py
telethon.network.connection.tcpfull.ConnectionTcpFull
class ConnectionTcpFull(Connection): """ Default Telegram mode. Sends 12 additional bytes and needs to calculate the CRC value of the packet itself. """ packet_codec = FullPacketCodec
class ConnectionTcpFull(Connection): ''' Default Telegram mode. Sends 12 additional bytes and needs to calculate the CRC value of the packet itself. ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
35
6
0
2
2
1
4
2
2
1
0
5
0
0
146,721
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpabridged.py
telethon.network.connection.tcpabridged.ConnectionTcpAbridged
class ConnectionTcpAbridged(Connection): """ This is the mode with the lowest overhead, as it will only require 1 byte if the packet length is less than 508 bytes (127 << 2, which is very common). """ packet_codec = AbridgedPacketCodec
class ConnectionTcpAbridged(Connection): ''' This is the mode with the lowest overhead, as it will only require 1 byte if the packet length is less than 508 bytes (127 << 2, which is very common). ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
35
7
0
2
2
1
5
2
2
1
0
5
0
0
146,722
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpabridged.py
telethon.network.connection.tcpabridged.AbridgedPacketCodec
class AbridgedPacketCodec(PacketCodec): tag = b'\xef' obfuscate_tag = b'\xef\xef\xef\xef' def encode_packet(self, data): length = len(data) >> 2 if length < 127: length = struct.pack('B', length) else: length = b'\x7f' + int.to_bytes(length, 3, 'little') return length + data async def read_packet(self, reader): length = struct.unpack('<B', await reader.readexactly(1))[0] if length >= 127: length = struct.unpack( '<i', await reader.readexactly(3) + b'\0')[0] return await reader.readexactly(length << 2)
class AbridgedPacketCodec(PacketCodec): def encode_packet(self, data): pass async def read_packet(self, reader): pass
3
0
7
1
7
0
2
0
1
1
0
0
2
0
2
25
19
3
16
7
13
0
14
7
11
2
5
1
4
146,723
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/extensions/html.py
telethon.extensions.html.HTMLToTelegramParser
class HTMLToTelegramParser(HTMLParser): def __init__(self): super().__init__() self.text = '' self.entities = [] self._building_entities = {} self._open_tags = deque() self._open_tags_meta = deque() def handle_starttag(self, tag, attrs): self._open_tags.appendleft(tag) self._open_tags_meta.appendleft(None) attrs = dict(attrs) EntityType = None args = {} if tag == 'strong' or tag == 'b': EntityType = MessageEntityBold elif tag == 'em' or tag == 'i': EntityType = MessageEntityItalic elif tag == 'u': EntityType = MessageEntityUnderline elif tag == 'del' or tag == 's': EntityType = MessageEntityStrike elif tag == 'blockquote': EntityType = MessageEntityBlockquote elif tag == 'code': try: # If we're in the middle of a <pre> tag, this <code> tag is # probably intended for syntax highlighting. # # Syntax highlighting is set with # <code class='language-...'>codeblock</code> # inside <pre> tags pre = self._building_entities['pre'] try: pre.language = attrs['class'][len('language-'):] except KeyError: pass except KeyError: EntityType = MessageEntityCode elif tag == 'pre': EntityType = MessageEntityPre args['language'] = '' elif tag == 'a': try: url = attrs['href'] except KeyError: return if url.startswith('mailto:'): url = url[len('mailto:'):] EntityType = MessageEntityEmail else: if self.get_starttag_text() == url: EntityType = MessageEntityUrl else: EntityType = MessageEntityTextUrl args['url'] = del_surrogate(url) url = None self._open_tags_meta.popleft() self._open_tags_meta.appendleft(url) if EntityType and tag not in self._building_entities: self._building_entities[tag] = EntityType( offset=len(self.text), # The length will be determined when closing the tag. length=0, **args) def handle_data(self, text): previous_tag = self._open_tags[0] if len(self._open_tags) > 0 else '' if previous_tag == 'a': url = self._open_tags_meta[0] if url: text = url for tag, entity in self._building_entities.items(): entity.length += len(text) self.text += text def handle_endtag(self, tag): try: self._open_tags.popleft() self._open_tags_meta.popleft() except IndexError: pass entity = self._building_entities.pop(tag, None) if entity: self.entities.append(entity)
class HTMLToTelegramParser(HTMLParser): def __init__(self): pass def handle_starttag(self, tag, attrs): pass def handle_data(self, text): pass def handle_endtag(self, tag): pass
5
0
22
1
19
2
6
0.09
1
4
0
0
4
5
4
42
90
7
76
18
71
7
64
18
59
15
2
3
24
146,724
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/http.py
telethon.network.connection.http.HttpPacketCodec
class HttpPacketCodec(PacketCodec): tag = None obfuscate_tag = None def encode_packet(self, data): return ('POST /api HTTP/1.1\r\n' 'Host: {}:{}\r\n' 'Content-Type: application/x-www-form-urlencoded\r\n' 'Connection: keep-alive\r\n' 'Keep-Alive: timeout=100000, max=10000000\r\n' 'Content-Length: {}\r\n\r\n' .format(self._conn._ip, self._conn._port, len(data)) .encode('ascii') + data) async def read_packet(self, reader): while True: line = await reader.readline() if not line or line[-1] != b'\n': raise asyncio.IncompleteReadError(line, None) if line.lower().startswith(b'content-length: '): await reader.readexactly(2) length = int(line[16:-2]) return await reader.readexactly(length)
class HttpPacketCodec(PacketCodec): def encode_packet(self, data): pass async def read_packet(self, reader): pass
3
0
10
1
9
0
3
0
1
1
0
0
2
0
2
25
24
3
21
7
18
0
14
7
11
4
5
2
5
146,725
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpobfuscated.py
telethon.network.connection.tcpobfuscated.ObfuscatedIO
class ObfuscatedIO: header = None def __init__(self, connection): self._reader = connection._reader self._writer = connection._writer (self.header, self._encrypt, self._decrypt) = self.init_header(connection.packet_codec) @staticmethod def init_header(packet_codec): # Obfuscated messages secrets cannot start with any of these keywords = (b'PVrG', b'GET ', b'POST', b'\xee\xee\xee\xee') while True: random = os.urandom(64) if (random[0] != 0xef and random[:4] not in keywords and random[4:8] != b'\0\0\0\0'): break random = bytearray(random) random_reversed = random[55:7:-1] # Reversed (8, len=48) # Encryption has "continuous buffer" enabled encrypt_key = bytes(random[8:40]) encrypt_iv = bytes(random[40:56]) decrypt_key = bytes(random_reversed[:32]) decrypt_iv = bytes(random_reversed[32:48]) encryptor = AESModeCTR(encrypt_key, encrypt_iv) decryptor = AESModeCTR(decrypt_key, decrypt_iv) random[56:60] = packet_codec.obfuscate_tag random[56:64] = encryptor.encrypt(bytes(random))[56:64] return (random, encryptor, decryptor) async def readexactly(self, n): return self._decrypt.encrypt(await self._reader.readexactly(n)) def write(self, data): self._writer.write(self._encrypt.encrypt(data))
class ObfuscatedIO: def __init__(self, connection): pass @staticmethod def init_header(packet_codec): pass async def readexactly(self, n): pass def write(self, data): pass
6
0
9
1
7
1
2
0.09
0
3
1
0
3
4
4
4
43
9
32
20
26
3
27
18
22
3
0
2
6
146,726
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/common.py
telethon.errors.common.ReadCancelledError
class ReadCancelledError(Exception): """Occurs when a read operation was cancelled.""" def __init__(self): super().__init__('The read operation was cancelled.')
class ReadCancelledError(Exception): '''Occurs when a read operation was cancelled.''' def __init__(self): pass
2
1
2
0
2
0
1
0.33
1
1
0
0
1
0
1
11
4
0
3
2
1
1
3
2
1
1
3
0
1
146,727
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/mtprotoplainsender.py
telethon.network.mtprotoplainsender.MTProtoPlainSender
class MTProtoPlainSender: """ MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages) """ def __init__(self, connection, *, loggers): """ Initializes the MTProto plain sender. :param connection: the Connection to be used. """ self._state = MTProtoState(auth_key=None, loggers=loggers) self._connection = connection async def send(self, request): """ Sends and receives the result for the given request. """ body = bytes(request) msg_id = self._state._get_new_msg_id() await self._connection.send( struct.pack('<qqi', 0, msg_id, len(body)) + body ) body = await self._connection.recv() if len(body) < 8: raise InvalidBufferError(body) with BinaryReader(body) as reader: auth_key_id = reader.read_long() assert auth_key_id == 0, 'Bad auth_key_id' msg_id = reader.read_long() assert msg_id != 0, 'Bad msg_id' # ^ We should make sure that the read ``msg_id`` is greater # than our own ``msg_id``. However, under some circumstances # (bad system clock/working behind proxies) this seems to not # be the case, which would cause endless assertion errors. length = reader.read_int() assert length > 0, 'Bad length' # We could read length bytes and use those in a new reader to read # the next TLObject without including the padding, but since the # reader isn't used for anything else after this, it's unnecessary. return reader.tgread_object()
class MTProtoPlainSender: ''' MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages) ''' def __init__(self, connection, *, loggers): ''' Initializes the MTProto plain sender. :param connection: the Connection to be used. ''' pass async def send(self, request): ''' Sends and receives the result for the given request. ''' pass
3
3
20
3
10
7
2
0.86
0
3
2
0
2
2
2
2
45
6
21
10
18
18
19
9
16
2
0
1
3
146,728
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/mtprotosender.py
telethon.network.mtprotosender.MTProtoSender
class MTProtoSender: """ MTProto Mobile Protocol sender (https://core.telegram.org/mtproto/description). This class is responsible for wrapping requests into `TLMessage`'s, sending them over the network and receiving them in a safe manner. Automatic reconnection due to temporary network issues is a concern for this class as well, including retry of messages that could not be sent successfully. A new authorization key will be generated on connection if no other key exists yet. """ def __init__(self, auth_key, *, loggers, retries=5, delay=1, auto_reconnect=True, connect_timeout=None, auth_key_callback=None, updates_queue=None, auto_reconnect_callback=None): self._connection = None self._loggers = loggers self._log = loggers[__name__] self._retries = retries self._delay = delay self._auto_reconnect = auto_reconnect self._connect_timeout = connect_timeout self._auth_key_callback = auth_key_callback self._updates_queue = updates_queue self._auto_reconnect_callback = auto_reconnect_callback self._connect_lock = asyncio.Lock() self._ping = None # Whether the user has explicitly connected or disconnected. # # If a disconnection happens for any other reason and it # was *not* user action then the pending messages won't # be cleared but on explicit user disconnection all the # pending futures should be cancelled. self._user_connected = False self._reconnecting = False self._disconnected = helpers.get_running_loop().create_future() self._disconnected.set_result(None) # We need to join the loops upon disconnection self._send_loop_handle = None self._recv_loop_handle = None # Preserving the references of the AuthKey and state is important self.auth_key = auth_key or AuthKey(None) self._state = MTProtoState(self.auth_key, loggers=self._loggers) # Outgoing messages are put in a queue and sent in a batch. # Note that here we're also storing their ``_RequestState``. self._send_queue = MessagePacker(self._state, loggers=self._loggers) # Sent states are remembered until a response is received. self._pending_state = {} # Responses must be acknowledged, and we can also batch these. self._pending_ack = set() # Similar to pending_messages but only for the last acknowledges. # These can't go in pending_messages because no acknowledge for them # is received, but we may still need to resend their state on bad salts. self._last_acks = collections.deque(maxlen=10) # Jump table from response ID to method that handles it self._handlers = { RpcResult.CONSTRUCTOR_ID: self._handle_rpc_result, MessageContainer.CONSTRUCTOR_ID: self._handle_container, GzipPacked.CONSTRUCTOR_ID: self._handle_gzip_packed, Pong.CONSTRUCTOR_ID: self._handle_pong, BadServerSalt.CONSTRUCTOR_ID: self._handle_bad_server_salt, BadMsgNotification.CONSTRUCTOR_ID: self._handle_bad_notification, MsgDetailedInfo.CONSTRUCTOR_ID: self._handle_detailed_info, MsgNewDetailedInfo.CONSTRUCTOR_ID: self._handle_new_detailed_info, NewSessionCreated.CONSTRUCTOR_ID: self._handle_new_session_created, MsgsAck.CONSTRUCTOR_ID: self._handle_ack, FutureSalts.CONSTRUCTOR_ID: self._handle_future_salts, MsgsStateReq.CONSTRUCTOR_ID: self._handle_state_forgotten, MsgResendReq.CONSTRUCTOR_ID: self._handle_state_forgotten, MsgsAllInfo.CONSTRUCTOR_ID: self._handle_msg_all, DestroySessionOk.CONSTRUCTOR_ID: self._handle_destroy_session, DestroySessionNone.CONSTRUCTOR_ID: self._handle_destroy_session, DestroyAuthKeyOk.CONSTRUCTOR_ID: self._handle_destroy_auth_key, DestroyAuthKeyNone.CONSTRUCTOR_ID: self._handle_destroy_auth_key, DestroyAuthKeyFail.CONSTRUCTOR_ID: self._handle_destroy_auth_key, } # Public API async def connect(self, connection): """ Connects to the specified given connection using the given auth key. """ async with self._connect_lock: if self._user_connected: self._log.info('User is already connected!') return False self._connection = connection await self._connect() self._user_connected = True return True def is_connected(self): return self._user_connected def _transport_connected(self): return ( not self._reconnecting and self._connection is not None and self._connection._connected ) async def disconnect(self): """ Cleanly disconnects the instance from the network, cancels all pending requests, and closes the send and receive loops. """ await self._disconnect() def send(self, request, ordered=False): """ This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def method(): # Sending (enqueued for the send loop) future = sender.send(request) # Receiving (waits for the receive loop to read the result) result = await future Designed like this because Telegram may send the response at any point, and it can send other items while one waits for it. Once the response for this future arrives, it is set with the received result, quite similar to how a ``receive()`` call would otherwise work. Since the receiving part is "built in" the future, it's impossible to await receive a result that was never sent. """ if not self._user_connected: raise ConnectionError('Cannot send requests while disconnected') if not utils.is_list_like(request): try: state = RequestState(request) except struct.error as e: # "struct.error: required argument is not an integer" is not # very helpful; log the request to find out what wasn't int. self._log.error('Request caused struct.error: %s: %s', e, request) raise self._send_queue.append(state) return state.future else: states = [] futures = [] state = None for req in request: try: state = RequestState(req, after=ordered and state) except struct.error as e: self._log.error('Request caused struct.error: %s: %s', e, request) raise states.append(state) futures.append(state.future) self._send_queue.extend(states) return futures @property def disconnected(self): """ Future that resolves when the connection to Telegram ends, either by user action or in the background. Note that it may resolve in either a ``ConnectionError`` or any other unexpected error that could not be handled. """ return asyncio.shield(self._disconnected) # Private methods async def _connect(self): """ Performs the actual connection, retrying, generating the authorization key if necessary, and starting the send and receive loops. """ self._log.info('Connecting to %s...', self._connection) connected = False for attempt in retry_range(self._retries): if not connected: connected = await self._try_connect(attempt) if not connected: continue # skip auth key generation until we're connected if not self.auth_key: try: if not await self._try_gen_auth_key(attempt): continue # keep retrying until we have the auth key except (IOError, asyncio.TimeoutError) as e: # Sometimes, specially during user-DC migrations, # Telegram may close the connection during auth_key # generation. If that's the case, we will need to # connect again. self._log.warning('Connection error %d during auth_key gen: %s: %s', attempt, type(e).__name__, e) # Whatever the IOError was, make sure to disconnect so we can # reconnect cleanly after. await self._connection.disconnect() connected = False await asyncio.sleep(self._delay) continue # next iteration we will try to reconnect break # all steps done, break retry loop else: if not connected: raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries)) e = ConnectionError('auth_key generation failed {} time(s)'.format(self._retries)) await self._disconnect(error=e) raise e loop = helpers.get_running_loop() self._log.debug('Starting send loop') self._send_loop_handle = loop.create_task(self._send_loop()) self._log.debug('Starting receive loop') self._recv_loop_handle = loop.create_task(self._recv_loop()) # _disconnected only completes after manual disconnection # or errors after which the sender cannot continue such # as failing to reconnect or any unexpected error. if self._disconnected.done(): self._disconnected = loop.create_future() self._log.info('Connection to %s complete!', self._connection) async def _try_connect(self, attempt): try: self._log.debug('Connection attempt %d...', attempt) await self._connection.connect(timeout=self._connect_timeout) self._log.debug('Connection success!') return True except (IOError, asyncio.TimeoutError) as e: self._log.warning('Attempt %d at connecting failed: %s: %s', attempt, type(e).__name__, e) await asyncio.sleep(self._delay) return False async def _try_gen_auth_key(self, attempt): plain = MTProtoPlainSender(self._connection, loggers=self._loggers) try: self._log.debug('New auth_key attempt %d...', attempt) self.auth_key.key, self._state.time_offset = \ await authenticator.do_authentication(plain) # This is *EXTREMELY* important since we don't control # external references to the authorization key, we must # notify whenever we change it. This is crucial when we # switch to different data centers. if self._auth_key_callback: self._auth_key_callback(self.auth_key) self._log.debug('auth_key generation success!') return True except (SecurityError, AssertionError) as e: self._log.warning('Attempt %d at new auth_key failed: %s', attempt, e) await asyncio.sleep(self._delay) return False async def _disconnect(self, error=None): if self._connection is None: self._log.info('Not disconnecting (already have no connection)') return self._log.info('Disconnecting from %s...', self._connection) self._user_connected = False try: self._log.debug('Closing current connection...') await self._connection.disconnect() finally: self._log.debug('Cancelling %d pending message(s)...', len(self._pending_state)) for state in self._pending_state.values(): if error and not state.future.done(): state.future.set_exception(error) else: state.future.cancel() self._pending_state.clear() await helpers._cancel( self._log, send_loop_handle=self._send_loop_handle, recv_loop_handle=self._recv_loop_handle ) self._log.info('Disconnection from %s complete!', self._connection) self._connection = None if self._disconnected and not self._disconnected.done(): if error: self._disconnected.set_exception(error) else: self._disconnected.set_result(None) async def _reconnect(self, last_error): """ Cleanly disconnects and then reconnects. """ self._log.info('Closing current connection to begin reconnect...') await self._connection.disconnect() await helpers._cancel( self._log, send_loop_handle=self._send_loop_handle, recv_loop_handle=self._recv_loop_handle ) # TODO See comment in `_start_reconnect` # Perhaps this should be the last thing to do? # But _connect() creates tasks which may run and, # if they see that reconnecting is True, they will end. # Perhaps that task creation should not belong in connect? self._reconnecting = False # Start with a clean state (and thus session ID) to avoid old msgs self._state.reset() retries = self._retries if self._auto_reconnect else 0 attempt = 0 ok = True # We're already "retrying" to connect, so we don't want to force retries for attempt in retry_range(retries, force_retry=False): try: await self._connect() except (IOError, asyncio.TimeoutError) as e: last_error = e self._log.info('Failed reconnection attempt %d with %s', attempt, e.__class__.__name__) await asyncio.sleep(self._delay) except BufferError as e: # TODO there should probably only be one place to except all these errors if isinstance(e, InvalidBufferError) and e.code == 404: self._log.info('Server does not know about the current auth key; the session may need to be recreated') last_error = AuthKeyNotFound() ok = False break else: self._log.warning('Invalid buffer %s', e) except Exception as e: last_error = e self._log.exception('Unexpected exception reconnecting on ' 'attempt %d', attempt) await asyncio.sleep(self._delay) else: self._send_queue.extend(self._pending_state.values()) self._pending_state.clear() if self._auto_reconnect_callback: helpers.get_running_loop().create_task(self._auto_reconnect_callback()) break else: ok = False if not ok: self._log.error('Automatic reconnection failed %d time(s)', attempt) # There may be no error (e.g. automatic reconnection was turned off). error = last_error.with_traceback(None) if last_error else None await self._disconnect(error=error) def _start_reconnect(self, error): """Starts a reconnection in the background.""" if self._user_connected and not self._reconnecting: # We set reconnecting to True here and not inside the new task # because it may happen that send/recv loop calls this again # while the new task hasn't had a chance to run yet. This race # condition puts `self.connection` in a bad state with two calls # to its `connect` without disconnecting, so it creates a second # receive loop. There can't be two tasks receiving data from # the reader, since that causes an error, and the library just # gets stuck. # TODO It still gets stuck? Investigate where and why. self._reconnecting = True helpers.get_running_loop().create_task(self._reconnect(error)) def _keepalive_ping(self, rnd_id): """ Send a keep-alive ping. If a pong for the last ping was not received yet, this means we're probably not connected. """ # TODO this is ugly, update loop shouldn't worry about this, sender should if self._ping is None: self._ping = rnd_id self.send(PingRequest(rnd_id)) else: self._start_reconnect(None) # Loops async def _send_loop(self): """ This loop is responsible for popping items off the send queue, encrypting them, and sending them over the network. Besides `connect`, only this method ever sends data. """ while self._user_connected and not self._reconnecting: if self._pending_ack: ack = RequestState(MsgsAck(list(self._pending_ack))) self._send_queue.append(ack) self._last_acks.append(ack) self._pending_ack.clear() self._log.debug('Waiting for messages to send...') # TODO Wait for the connection send queue to be empty? # This means that while it's not empty we can wait for # more messages to be added to the send queue. batch, data = await self._send_queue.get() if not data: continue self._log.debug('Encrypting %d message(s) in %d bytes for sending', len(batch), len(data)) data = self._state.encrypt_message_data(data) # Whether sending succeeds or not, the popped requests are now # pending because they're removed from the queue. If a reconnect # occurs, they will be removed from pending state and re-enqueued # so even if the network fails they won't be lost. If they were # never re-enqueued, the future waiting for a response "locks". for state in batch: if not isinstance(state, list): if isinstance(state.request, TLRequest): self._pending_state[state.msg_id] = state else: for s in state: if isinstance(s.request, TLRequest): self._pending_state[s.msg_id] = s try: await self._connection.send(data) except IOError as e: self._log.info('Connection closed while sending data') self._start_reconnect(e) return self._log.debug('Encrypted messages put in a queue to be sent') async def _recv_loop(self): """ This loop is responsible for reading all incoming responses from the network, decrypting and handling or dispatching them. Besides `connect`, only this method ever receives data. """ while self._user_connected and not self._reconnecting: self._log.debug('Receiving items from the network...') try: body = await self._connection.recv() except asyncio.CancelledError: raise # bypass except Exception except (IOError, asyncio.IncompleteReadError) as e: self._log.info('Connection closed while receiving data: %s', e) self._start_reconnect(e) return except InvalidBufferError as e: if e.code == 429: self._log.warning('Server indicated flood error at transport level: %s', e) await self._disconnect(error=e) else: self._log.exception('Server sent invalid buffer') self._start_reconnect(e) return except Exception as e: self._log.exception('Unhandled error while receiving data') self._start_reconnect(e) return try: message = self._state.decrypt_message_data(body) if message is None: continue # this message is to be ignored except TypeNotFoundError as e: # Received object which we don't know how to deserialize self._log.info('Type %08x not found, remaining data %r', e.invalid_constructor_id, e.remaining) continue except SecurityError as e: # A step while decoding had the incorrect data. This message # should not be considered safe and it should be ignored. self._log.warning('Security error while unpacking a ' 'received message: %s', e) continue except BufferError as e: if isinstance(e, InvalidBufferError) and e.code == 404: self._log.info('Server does not know about the current auth key; the session may need to be recreated') await self._disconnect(error=AuthKeyNotFound()) else: self._log.warning('Invalid buffer %s', e) self._start_reconnect(e) return except Exception as e: self._log.exception('Unhandled error while decrypting data') self._start_reconnect(e) return try: await self._process_message(message) except Exception: self._log.exception('Unhandled error while processing msgs') # Response Handlers async def _process_message(self, message): """ Adds the given message to the list of messages that must be acknowledged and dispatches control to different ``_handle_*`` method based on its type. """ self._pending_ack.add(message.msg_id) handler = self._handlers.get(message.obj.CONSTRUCTOR_ID, self._handle_update) await handler(message) def _pop_states(self, msg_id): """ Pops the states known to match the given ID from pending messages. This method should be used when the response isn't specific. """ state = self._pending_state.pop(msg_id, None) if state: return [state] to_pop = [] for state in self._pending_state.values(): if state.container_id == msg_id: to_pop.append(state.msg_id) if to_pop: return [self._pending_state.pop(x) for x in to_pop] for ack in self._last_acks: if ack.msg_id == msg_id: return [ack] return [] async def _handle_rpc_result(self, message): """ Handles the result for Remote Procedure Calls: rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult; This is where the future results for sent requests are set. """ rpc_result = message.obj state = self._pending_state.pop(rpc_result.req_msg_id, None) self._log.debug('Handling RPC result for message %d', rpc_result.req_msg_id) if not state: # TODO We should not get responses to things we never sent # However receiving a File() with empty bytes is "common". # See #658, #759 and #958. They seem to happen in a container # which contain the real response right after. # # But, it might also happen that we get an *error* for no parent request. # If that's the case attempting to read from body which is None would fail with: # "BufferError: No more data left to read (need 4, got 0: b''); last read None". # This seems to be particularly common for "RpcError(error_code=-500, error_message='No workers running')". if rpc_result.error: self._log.info('Received error without parent request: %s', rpc_result.error) else: try: with BinaryReader(rpc_result.body) as reader: if not isinstance(reader.tgread_object(), upload.File): raise ValueError('Not an upload.File') except (TypeNotFoundError, ValueError): self._log.info('Received response without parent request: %s', rpc_result.body) return if rpc_result.error: error = rpc_message_to_error(rpc_result.error, state.request) self._send_queue.append( RequestState(MsgsAck([state.msg_id]))) if not state.future.cancelled(): state.future.set_exception(error) else: try: with BinaryReader(rpc_result.body) as reader: result = state.request.read_result(reader) except Exception as e: # e.g. TypeNotFoundError, should be propagated to caller if not state.future.cancelled(): state.future.set_exception(e) else: self._store_own_updates(result) if not state.future.cancelled(): state.future.set_result(result) async def _handle_container(self, message): """ Processes the inner messages of a container with many of them: msg_container#73f1f8dc messages:vector<%Message> = MessageContainer; """ self._log.debug('Handling container') for inner_message in message.obj.messages: await self._process_message(inner_message) async def _handle_gzip_packed(self, message): """ Unpacks the data from a gzipped object and processes it: gzip_packed#3072cfa1 packed_data:bytes = Object; """ self._log.debug('Handling gzipped data') with BinaryReader(message.obj.data) as reader: message.obj = reader.tgread_object() await self._process_message(message) async def _handle_update(self, message): try: assert message.obj.SUBCLASS_OF_ID == 0x8af52aac # crc32(b'Updates') except AssertionError: self._log.warning( 'Note: %s is not an update, not dispatching it %s', message.obj.__class__.__name__, message.obj ) return self._log.debug('Handling update %s', message.obj.__class__.__name__) self._updates_queue.put_nowait(message.obj) def _store_own_updates(self, obj, *, _update_ids=frozenset(( _tl.UpdateShortMessage.CONSTRUCTOR_ID, _tl.UpdateShortChatMessage.CONSTRUCTOR_ID, _tl.UpdateShort.CONSTRUCTOR_ID, _tl.UpdatesCombined.CONSTRUCTOR_ID, _tl.Updates.CONSTRUCTOR_ID, _tl.UpdateShortSentMessage.CONSTRUCTOR_ID, )), _update_like_ids=frozenset(( _tl.messages.AffectedHistory.CONSTRUCTOR_ID, _tl.messages.AffectedMessages.CONSTRUCTOR_ID, _tl.messages.AffectedFoundMessages.CONSTRUCTOR_ID, ))): try: if obj.CONSTRUCTOR_ID in _update_ids: obj._self_outgoing = True # flag to only process, but not dispatch these self._updates_queue.put_nowait(obj) elif obj.CONSTRUCTOR_ID in _update_like_ids: # Ugly "hack" (?) - otherwise bots reliably detect gaps when deleting messages. # # Note: the `date` being `None` is used to check for `updatesTooLong`, so epoch # is used instead. It is still not read, because `updateShort` has no `seq`. # # Some requests, such as `readHistory`, also return these types. But the `pts_count` # seems to be zero, so while this will produce some bogus `updateDeleteMessages`, # it's still one of the "cleaner" approaches to handling the new `pts`. # `updateDeleteMessages` is probably the "least-invasive" update that can be used. upd = _tl.UpdateShort( _tl.UpdateDeleteMessages([], obj.pts, obj.pts_count), datetime.datetime(*time.gmtime(0)[:6]).replace(tzinfo=datetime.timezone.utc) ) upd._self_outgoing = True self._updates_queue.put_nowait(upd) elif obj.CONSTRUCTOR_ID == _tl.messages.InvitedUsers.CONSTRUCTOR_ID: obj.updates._self_outgoing = True self._updates_queue.put_nowait(obj.updates) except AttributeError: pass async def _handle_pong(self, message): """ Handles pong results, which don't come inside a ``rpc_result`` but are still sent through a request: pong#347773c5 msg_id:long ping_id:long = Pong; """ pong = message.obj self._log.debug('Handling pong for message %d', pong.msg_id) if self._ping == pong.ping_id: self._ping = None state = self._pending_state.pop(pong.msg_id, None) if state: state.future.set_result(pong) async def _handle_bad_server_salt(self, message): """ Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification; """ bad_salt = message.obj self._log.debug('Handling bad salt for message %d', bad_salt.bad_msg_id) self._state.salt = bad_salt.new_server_salt states = self._pop_states(bad_salt.bad_msg_id) self._send_queue.extend(states) self._log.debug('%d message(s) will be resent', len(states)) async def _handle_bad_notification(self, message): """ Adjusts the current state to be correct based on the received bad message notification whenever possible: bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification; """ bad_msg = message.obj states = self._pop_states(bad_msg.bad_msg_id) self._log.debug('Handling bad msg %s', bad_msg) if bad_msg.error_code in (16, 17): # Sent msg_id too low or too high (respectively). # Use the current msg_id to determine the right time offset. to = self._state.update_time_offset( correct_msg_id=message.msg_id) self._log.info('System clock is wrong, set time offset to %ds', to) elif bad_msg.error_code == 32: # msg_seqno too low, so just pump it up by some "large" amount # TODO A better fix would be to start with a new fresh session ID self._state._sequence += 64 elif bad_msg.error_code == 33: # msg_seqno too high never seems to happen but just in case self._state._sequence -= 16 else: for state in states: state.future.set_exception( BadMessageError(state.request, bad_msg.error_code)) return # Messages are to be re-sent once we've corrected the issue self._send_queue.extend(states) self._log.debug('%d messages will be resent due to bad msg', len(states)) async def _handle_detailed_info(self, message): """ Updates the current status with the received detailed information: msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo; """ # TODO https://goo.gl/VvpCC6 msg_id = message.obj.answer_msg_id self._log.debug('Handling detailed info for message %d', msg_id) self._pending_ack.add(msg_id) async def _handle_new_detailed_info(self, message): """ Updates the current status with the received detailed information: msg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo; """ # TODO https://goo.gl/G7DPsR msg_id = message.obj.answer_msg_id self._log.debug('Handling new detailed info for message %d', msg_id) self._pending_ack.add(msg_id) async def _handle_new_session_created(self, message): """ Updates the current status with the received session information: new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession; """ # TODO https://goo.gl/LMyN7A self._log.debug('Handling new session created') self._state.salt = message.obj.server_salt async def _handle_ack(self, message): """ Handles a server acknowledge about our messages. Normally these can be ignored except in the case of ``auth.logOut``: auth.logOut#5717da40 = Bool; Telegram doesn't seem to send its result so we need to confirm it manually. No other request is known to have this behaviour. Since the ID of sent messages consisting of a container is never returned (unless on a bad notification), this method also removes containers messages when any of their inner messages are acknowledged. """ ack = message.obj self._log.debug('Handling acknowledge for %s', str(ack.msg_ids)) for msg_id in ack.msg_ids: state = self._pending_state.get(msg_id) if state and isinstance(state.request, LogOutRequest): del self._pending_state[msg_id] if not state.future.cancelled(): state.future.set_result(True) async def _handle_future_salts(self, message): """ Handles future salt results, which don't come inside a ``rpc_result`` but are still sent through a request: future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts; """ # TODO save these salts and automatically adjust to the # correct one whenever the salt in use expires. self._log.debug('Handling future salts for message %d', message.msg_id) state = self._pending_state.pop(message.msg_id, None) if state: state.future.set_result(message.obj) async def _handle_state_forgotten(self, message): """ Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by enqueuing a :tl:`MsgsStateInfo` to be sent at a later point. """ self._send_queue.append(RequestState(MsgsStateInfo( req_msg_id=message.msg_id, info=chr(1) * len(message.obj.msg_ids) ))) async def _handle_msg_all(self, message): """ Handles :tl:`MsgsAllInfo` by doing nothing (yet). """ async def _handle_destroy_session(self, message): """ Handles both :tl:`DestroySessionOk` and :tl:`DestroySessionNone`. It behaves pretty much like handling an RPC result. """ for msg_id, state in self._pending_state.items(): if isinstance(state.request, DestroySessionRequest)\ and state.request.session_id == message.obj.session_id: break else: return del self._pending_state[msg_id] if not state.future.cancelled(): state.future.set_result(message.obj) async def _handle_destroy_auth_key(self, message): """ Handles :tl:`DestroyAuthKeyFail`, :tl:`DestroyAuthKeyNone`, and :tl:`DestroyAuthKeyOk`. :tl:`DestroyAuthKey` is not intended for users to use, but they still might, and the response won't come in `rpc_result`, so thhat's worked around here. """ self._log.debug('Handling destroy auth key %s', message.obj) for msg_id, state in list(self._pending_state.items()): if isinstance(state.request, DestroyAuthKeyRequest): del self._pending_state[msg_id] if not state.future.cancelled(): state.future.set_result(message.obj) # If the auth key has been destroyed, that pretty much means the # library can't continue as our auth key will no longer be found # on the server. # Even if the library didn't disconnect, the server would (and then # the library would reconnect and learn about auth key being invalid). if isinstance(message.obj, DestroyAuthKeyOk): await self._disconnect(error=AuthKeyNotFound())
class MTProtoSender: ''' MTProto Mobile Protocol sender (https://core.telegram.org/mtproto/description). This class is responsible for wrapping requests into `TLMessage`'s, sending them over the network and receiving them in a safe manner. Automatic reconnection due to temporary network issues is a concern for this class as well, including retry of messages that could not be sent successfully. A new authorization key will be generated on connection if no other key exists yet. ''' def __init__(self, auth_key, *, loggers, retries=5, delay=1, auto_reconnect=True, connect_timeout=None, auth_key_callback=None, updates_queue=None, auto_reconnect_callback=None): pass async def connect(self, connection): ''' Connects to the specified given connection using the given auth key. ''' pass def is_connected(self): pass def _transport_connected(self): pass async def disconnect(self): ''' Cleanly disconnects the instance from the network, cancels all pending requests, and closes the send and receive loops. ''' pass def send(self, request, ordered=False): ''' This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def method(): # Sending (enqueued for the send loop) future = sender.send(request) # Receiving (waits for the receive loop to read the result) result = await future Designed like this because Telegram may send the response at any point, and it can send other items while one waits for it. Once the response for this future arrives, it is set with the received result, quite similar to how a ``receive()`` call would otherwise work. Since the receiving part is "built in" the future, it's impossible to await receive a result that was never sent. ''' pass @property def disconnected(self): ''' Future that resolves when the connection to Telegram ends, either by user action or in the background. Note that it may resolve in either a ``ConnectionError`` or any other unexpected error that could not be handled. ''' pass async def _connect(self): ''' Performs the actual connection, retrying, generating the authorization key if necessary, and starting the send and receive loops. ''' pass async def _try_connect(self, attempt): pass async def _try_gen_auth_key(self, attempt): pass async def _disconnect(self, error=None): pass async def _reconnect(self, last_error): ''' Cleanly disconnects and then reconnects. ''' pass def _start_reconnect(self, error): '''Starts a reconnection in the background.''' pass def _keepalive_ping(self, rnd_id): ''' Send a keep-alive ping. If a pong for the last ping was not received yet, this means we're probably not connected. ''' pass async def _send_loop(self): ''' This loop is responsible for popping items off the send queue, encrypting them, and sending them over the network. Besides `connect`, only this method ever sends data. ''' pass async def _recv_loop(self): ''' This loop is responsible for reading all incoming responses from the network, decrypting and handling or dispatching them. Besides `connect`, only this method ever receives data. ''' pass async def _process_message(self, message): ''' Adds the given message to the list of messages that must be acknowledged and dispatches control to different ``_handle_*`` method based on its type. ''' pass def _pop_states(self, msg_id): ''' Pops the states known to match the given ID from pending messages. This method should be used when the response isn't specific. ''' pass async def _handle_rpc_result(self, message): ''' Handles the result for Remote Procedure Calls: rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult; This is where the future results for sent requests are set. ''' pass async def _handle_container(self, message): ''' Processes the inner messages of a container with many of them: msg_container#73f1f8dc messages:vector<%Message> = MessageContainer; ''' pass async def _handle_gzip_packed(self, message): ''' Unpacks the data from a gzipped object and processes it: gzip_packed#3072cfa1 packed_data:bytes = Object; ''' pass async def _handle_update(self, message): pass def _store_own_updates(self, obj, *, _update_ids=frozenset(( _tl.UpdateShortMessage.CONSTRUCTOR_ID, _tl.UpdateShortChatMessage.CONSTRUCTOR_ID, _tl.UpdateShort.CONSTRUCTOR_ID, _tl.UpdatesCombined.CONSTRUCTOR_ID, _tl.Updates.CONSTRUCTOR_ID, _tl.UpdateShortSentMessage.CONSTRUCTOR_ID, )), _update_like_ids=frozenset(( _tl.messages.AffectedHistory.CONSTRUCTOR_ID, _tl.messages.AffectedMessages.CONSTRUCTOR_ID, _tl.messages.AffectedFoundMessages.CONSTRUCTOR_ID, ))): pass async def _handle_pong(self, message): ''' Handles pong results, which don't come inside a ``rpc_result`` but are still sent through a request: pong#347773c5 msg_id:long ping_id:long = Pong; ''' pass async def _handle_bad_server_salt(self, message): ''' Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification; ''' pass async def _handle_bad_notification(self, message): ''' Adjusts the current state to be correct based on the received bad message notification whenever possible: bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification; ''' pass async def _handle_detailed_info(self, message): ''' Updates the current status with the received detailed information: msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo; ''' pass async def _handle_new_detailed_info(self, message): ''' Updates the current status with the received detailed information: msg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo; ''' pass async def _handle_new_session_created(self, message): ''' Updates the current status with the received session information: new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession; ''' pass async def _handle_ack(self, message): ''' Handles a server acknowledge about our messages. Normally these can be ignored except in the case of ``auth.logOut``: auth.logOut#5717da40 = Bool; Telegram doesn't seem to send its result so we need to confirm it manually. No other request is known to have this behaviour. Since the ID of sent messages consisting of a container is never returned (unless on a bad notification), this method also removes containers messages when any of their inner messages are acknowledged. ''' pass async def _handle_future_salts(self, message): ''' Handles future salt results, which don't come inside a ``rpc_result`` but are still sent through a request: future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts; ''' pass async def _handle_state_forgotten(self, message): ''' Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by enqueuing a :tl:`MsgsStateInfo` to be sent at a later point. ''' pass async def _handle_msg_all(self, message): ''' Handles :tl:`MsgsAllInfo` by doing nothing (yet). ''' pass async def _handle_destroy_session(self, message): ''' Handles both :tl:`DestroySessionOk` and :tl:`DestroySessionNone`. It behaves pretty much like handling an RPC result. ''' pass async def _handle_destroy_auth_key(self, message): ''' Handles :tl:`DestroyAuthKeyFail`, :tl:`DestroyAuthKeyNone`, and :tl:`DestroyAuthKeyOk`. :tl:`DestroyAuthKey` is not intended for users to use, but they still might, and the response won't come in `rpc_result`, so thhat's worked around here. ''' pass
37
28
24
2
14
7
4
0.52
0
24
10
0
35
24
35
35
886
127
506
130
455
261
419
105
383
14
0
5
128
146,729
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/mtprotostate.py
telethon.network.mtprotostate.MTProtoState
class MTProtoState: """ `telethon.network.mtprotosender.MTProtoSender` needs to hold a state in order to be able to encrypt and decrypt incoming/outgoing messages, as well as generating the message IDs. Instances of this class hold together all the required information. It doesn't make sense to use `telethon.sessions.abstract.Session` for the sender because the sender should *not* be concerned about storing this information to disk, as one may create as many senders as they desire to any other data center, or some CDN. Using the same session for all these is not a good idea as each need their own authkey, and the concept of "copying" sessions with the unnecessary entities or updates state for these connections doesn't make sense. While it would be possible to have a `MTProtoPlainState` that does no encryption so that it was usable through the `MTProtoLayer` and thus avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more focused to efficiency and this state is also more advanced (since it supports gzipping and invoking after other message IDs). There are too many methods that would be needed to make it convenient to use for the authentication process, at which point the `MTProtoPlainSender` is better. """ def __init__(self, auth_key, loggers): self.auth_key = auth_key self._log = loggers[__name__] self.time_offset = 0 self.salt = 0 self.id = self._sequence = self._last_msg_id = None self._recent_remote_ids = deque(maxlen=MAX_RECENT_MSG_IDS) self._highest_remote_id = 0 self._ignore_count = 0 self.reset() def reset(self): """ Resets the state. """ # Session IDs can be random on every connection self.id = struct.unpack('q', os.urandom(8))[0] self._sequence = 0 self._last_msg_id = 0 self._recent_remote_ids.clear() self._highest_remote_id = 0 self._ignore_count = 0 def update_message_id(self, message): """ Updates the message ID to a new one, used when the time offset changed. """ message.msg_id = self._get_new_msg_id() @staticmethod def _calc_key(auth_key, msg_key, client): """ Calculate the key based on Telegram guidelines for MTProto 2, specifying whether it's the client or not. See https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector """ x = 0 if client else 8 sha256a = sha256(msg_key + auth_key[x: x + 36]).digest() sha256b = sha256(auth_key[x + 40:x + 76] + msg_key).digest() aes_key = sha256a[:8] + sha256b[8:24] + sha256a[24:32] aes_iv = sha256b[:8] + sha256a[8:24] + sha256b[24:32] return aes_key, aes_iv def write_data_as_message(self, buffer, data, content_related, *, after_id=None): """ Writes a message containing the given data into buffer. Returns the message id. """ msg_id = self._get_new_msg_id() seq_no = self._get_seq_no(content_related) if after_id is None: body = GzipPacked.gzip_if_smaller(content_related, data) else: # The `RequestState` stores `bytes(request)`, not the request itself. # `invokeAfterMsg` wants a `TLRequest` though, hence the wrapping. body = GzipPacked.gzip_if_smaller(content_related, bytes(InvokeAfterMsgRequest(after_id, _OpaqueRequest(data)))) buffer.write(struct.pack('<qii', msg_id, seq_no, len(body))) buffer.write(body) return msg_id def encrypt_message_data(self, data): """ Encrypts the given message data using the current authorization key following MTProto 2.0 guidelines core.telegram.org/mtproto/description. """ data = struct.pack('<qq', self.salt, self.id) + data padding = os.urandom(-(len(data) + 12) % 16 + 12) # Being substr(what, offset, length); x = 0 for client # "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)" msg_key_large = sha256( self.auth_key.key[88:88 + 32] + data + padding).digest() # "msg_key = substr (msg_key_large, 8, 16)" msg_key = msg_key_large[8:24] aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, True) key_id = struct.pack('<Q', self.auth_key.key_id) return (key_id + msg_key + AES.encrypt_ige(data + padding, aes_key, aes_iv)) def decrypt_message_data(self, body): """ Inverse of `encrypt_message_data` for incoming server messages. """ now = time.time() + self.time_offset # get the time as early as possible, even if other checks make it go unused if len(body) < 8: raise InvalidBufferError(body) # TODO Check salt, session_id and sequence_number key_id = struct.unpack('<Q', body[:8])[0] if key_id != self.auth_key.key_id: raise SecurityError('Server replied with an invalid auth key') msg_key = body[8:24] aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, False) body = AES.decrypt_ige(body[24:], aes_key, aes_iv) # https://core.telegram.org/mtproto/security_guidelines # Sections "checking sha256 hash" and "message length" our_key = sha256(self.auth_key.key[96:96 + 32] + body) if msg_key != our_key.digest()[8:24]: raise SecurityError( "Received msg_key doesn't match with expected one") reader = BinaryReader(body) reader.read_long() # remote_salt if reader.read_long() != self.id: raise SecurityError('Server replied with a wrong session ID (see FAQ for details)') remote_msg_id = reader.read_long() if remote_msg_id % 2 != 1: raise SecurityError('Server sent an even msg_id') # Only perform the (somewhat expensive) check of duplicate if we did receive a lower ID if remote_msg_id <= self._highest_remote_id and remote_msg_id in self._recent_remote_ids: self._log.warning('Server resent the older message %d, ignoring', remote_msg_id) self._count_ignored() return None remote_sequence = reader.read_int() reader.read_int() # msg_len for the inner object, padding ignored # We could read msg_len bytes and use those in a new reader to read # the next TLObject without including the padding, but since the # reader isn't used for anything else after this, it's unnecessary. obj = reader.tgread_object() # "Certain client-to-server service messages containing data sent by the client to the # server (for example, msg_id of a recent client query) may, nonetheless, be processed # on the client even if the time appears to be "incorrect". This is especially true of # messages to change server_salt and notifications about invalid time on the client." # # This means we skip the time check for certain types of messages. if obj.CONSTRUCTOR_ID not in (BadServerSalt.CONSTRUCTOR_ID, BadMsgNotification.CONSTRUCTOR_ID): remote_msg_time = remote_msg_id >> 32 time_delta = now - remote_msg_time if time_delta > MSG_TOO_OLD_DELTA: self._log.warning('Server sent a very old message with ID %d, ignoring (see FAQ for details)', remote_msg_id) self._count_ignored() return None if -time_delta > MSG_TOO_NEW_DELTA: self._log.warning('Server sent a very new message with ID %d, ignoring (see FAQ for details)', remote_msg_id) self._count_ignored() return None self._recent_remote_ids.append(remote_msg_id) self._highest_remote_id = remote_msg_id self._ignore_count = 0 return TLMessage(remote_msg_id, remote_sequence, obj) def _count_ignored(self): # It's possible that ignoring a message "bricks" the connection, # but this should not happen unless there's something else wrong. self._ignore_count += 1 if self._ignore_count >= MAX_CONSECUTIVE_IGNORED: raise SecurityError('Too many messages had to be ignored consecutively') def _get_new_msg_id(self): """ Generates a new unique message ID based on the current time (in ms) since epoch, applying a known time offset. """ now = time.time() + self.time_offset nanoseconds = int((now - int(now)) * 1e+9) new_msg_id = (int(now) << 32) | (nanoseconds << 2) if self._last_msg_id >= new_msg_id: new_msg_id = self._last_msg_id + 4 self._last_msg_id = new_msg_id return new_msg_id def update_time_offset(self, correct_msg_id): """ Updates the time offset to the correct one given a known valid message ID. """ bad = self._get_new_msg_id() old = self.time_offset now = int(time.time()) correct = correct_msg_id >> 32 self.time_offset = correct - now if self.time_offset != old: self._last_msg_id = 0 self._log.debug( 'Updated time offset (old offset %d, bad %d, good %d, new %d)', old, bad, correct_msg_id, self.time_offset ) return self.time_offset def _get_seq_no(self, content_related): """ Generates the next sequence number depending on whether it should be for a content-related query or not. """ if content_related: result = self._sequence * 2 + 1 self._sequence += 1 return result else: return self._sequence * 2
class MTProtoState: ''' `telethon.network.mtprotosender.MTProtoSender` needs to hold a state in order to be able to encrypt and decrypt incoming/outgoing messages, as well as generating the message IDs. Instances of this class hold together all the required information. It doesn't make sense to use `telethon.sessions.abstract.Session` for the sender because the sender should *not* be concerned about storing this information to disk, as one may create as many senders as they desire to any other data center, or some CDN. Using the same session for all these is not a good idea as each need their own authkey, and the concept of "copying" sessions with the unnecessary entities or updates state for these connections doesn't make sense. While it would be possible to have a `MTProtoPlainState` that does no encryption so that it was usable through the `MTProtoLayer` and thus avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more focused to efficiency and this state is also more advanced (since it supports gzipping and invoking after other message IDs). There are too many methods that would be needed to make it convenient to use for the authentication process, at which point the `MTProtoPlainSender` is better. ''' def __init__(self, auth_key, loggers): pass def reset(self): ''' Resets the state. ''' pass def update_message_id(self, message): ''' Updates the message ID to a new one, used when the time offset changed. ''' pass @staticmethod def _calc_key(auth_key, msg_key, client): ''' Calculate the key based on Telegram guidelines for MTProto 2, specifying whether it's the client or not. See https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector ''' pass def write_data_as_message(self, buffer, data, content_related, *, after_id=None): ''' Writes a message containing the given data into buffer. Returns the message id. ''' pass def encrypt_message_data(self, data): ''' Encrypts the given message data using the current authorization key following MTProto 2.0 guidelines core.telegram.org/mtproto/description. ''' pass def decrypt_message_data(self, body): ''' Inverse of `encrypt_message_data` for incoming server messages. ''' pass def _count_ignored(self): pass def _get_new_msg_id(self): ''' Generates a new unique message ID based on the current time (in ms) since epoch, applying a known time offset. ''' pass def update_time_offset(self, correct_msg_id): ''' Updates the time offset to the correct one given a known valid message ID. ''' pass def _get_seq_no(self, content_related): ''' Generates the next sequence number depending on whether it should be for a content-related query or not. ''' pass
13
10
19
3
11
5
2
0.63
0
6
4
0
10
10
11
11
241
40
125
54
111
79
114
52
102
10
0
2
26
146,730
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/mtprotostate.py
telethon.network.mtprotostate._OpaqueRequest
class _OpaqueRequest(TLRequest): """ Wraps a serialized request into a type that can be serialized again. """ def __init__(self, data: bytes): self.data = data def _bytes(self): return self.data
class _OpaqueRequest(TLRequest): ''' Wraps a serialized request into a type that can be serialized again. ''' def __init__(self, data: bytes): pass def _bytes(self): pass
3
1
2
0
2
0
1
0.6
1
1
0
0
2
1
2
16
9
1
5
4
2
3
5
4
2
1
2
0
2
146,731
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/requeststate.py
telethon.network.requeststate.RequestState
class RequestState: """ This request state holds several information relevant to sent messages, in particular the message ID assigned to the request, the container ID it belongs to, the request itself, the request as bytes, and the future result that will eventually be resolved. """ __slots__ = ('container_id', 'msg_id', 'request', 'data', 'future', 'after') def __init__(self, request, after=None): self.container_id = None self.msg_id = None self.request = request self.data = bytes(request) self.future = asyncio.Future() self.after = after
class RequestState: ''' This request state holds several information relevant to sent messages, in particular the message ID assigned to the request, the container ID it belongs to, the request itself, the request as bytes, and the future result that will eventually be resolved. ''' def __init__(self, request, after=None): pass
2
1
7
0
7
0
1
0.67
0
1
0
0
1
6
1
1
16
1
9
9
7
6
9
9
7
1
0
0
1
146,732
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/http.py
telethon.network.connection.http.ConnectionHttp
class ConnectionHttp(Connection): packet_codec = HttpPacketCodec async def connect(self, timeout=None, ssl=None): await super().connect(timeout=timeout, ssl=self._port == SSL_PORT)
class ConnectionHttp(Connection): async def connect(self, timeout=None, ssl=None): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
36
5
1
4
3
2
0
4
3
2
1
5
0
1
146,733
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/connection.py
telethon.network.connection.connection.ObfuscatedConnection
class ObfuscatedConnection(Connection): """ Base class for "obfuscated" connections ("obfuscated2", "mtproto proxy") """ """ This attribute should be redefined by subclasses """ obfuscated_io = None def _init_conn(self): self._obfuscation = self.obfuscated_io(self) self._writer.write(self._obfuscation.header) def _send(self, data): self._obfuscation.write(self._codec.encode_packet(data)) async def _recv(self): return await self._codec.read_packet(self._obfuscation)
class ObfuscatedConnection(Connection): ''' Base class for "obfuscated" connections ("obfuscated2", "mtproto proxy") ''' def _init_conn(self): pass def _send(self, data): pass async def _recv(self): pass
4
1
2
0
2
0
1
0.67
1
0
0
2
3
1
3
38
18
3
9
6
5
6
9
6
5
1
5
0
3
146,734
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/helpers.py
telethon.helpers._FileStream
class _FileStream(io.IOBase): """ Proxy around things that represent a file and need to be used as streams which may or not need to be closed. This will handle `pathlib.Path`, `str` paths, in-memory `bytes`, and anything IO-like (including `aiofiles`). It also provides access to the name and file size (also necessary). """ def __init__(self, file, *, file_size=None): if isinstance(file, Path): file = str(file.absolute()) self._file = file self._name = None self._size = file_size self._stream = None self._close_stream = None async def __aenter__(self): if isinstance(self._file, str): self._name = os.path.basename(self._file) self._size = os.path.getsize(self._file) self._stream = open(self._file, 'rb') self._close_stream = True return self if isinstance(self._file, bytes): self._size = len(self._file) self._stream = io.BytesIO(self._file) self._close_stream = True return self if not callable(getattr(self._file, 'read', None)): raise TypeError('file description should have a `read` method') self._name = getattr(self._file, 'name', None) self._stream = self._file self._close_stream = False if self._size is None: if callable(getattr(self._file, 'seekable', None)): seekable = await _maybe_await(self._file.seekable()) else: seekable = False if seekable: pos = await _maybe_await(self._file.tell()) await _maybe_await(self._file.seek(0, os.SEEK_END)) self._size = await _maybe_await(self._file.tell()) await _maybe_await(self._file.seek(pos, os.SEEK_SET)) else: _log.warning( 'Could not determine file size beforehand so the entire ' 'file will be read in-memory') data = await _maybe_await(self._file.read()) self._size = len(data) self._stream = io.BytesIO(data) self._close_stream = True return self async def __aexit__(self, exc_type, exc_val, exc_tb): if self._close_stream and self._stream: await _maybe_await(self._stream.close()) @property def file_size(self): return self._size @property def name(self): return self._name # Proxy all the methods. Doesn't need to be readable (makes multiline edits easier) def read(self, *args, **kwargs): return self._stream.read(*args, **kwargs) def readinto(self, *args, **kwargs): return self._stream.readinto(*args, **kwargs) def write(self, *args, **kwargs): return self._stream.write(*args, **kwargs) def fileno(self, *args, **kwargs): return self._stream.fileno(*args, **kwargs) def flush(self, *args, **kwargs): return self._stream.flush(*args, **kwargs) def isatty(self, *args, **kwargs): return self._stream.isatty(*args, **kwargs) def readable(self, *args, **kwargs): return self._stream.readable(*args, **kwargs) def readline(self, *args, **kwargs): return self._stream.readline(*args, **kwargs) def readlines(self, *args, **kwargs): return self._stream.readlines(*args, **kwargs) def seek(self, *args, **kwargs): return self._stream.seek(*args, **kwargs) def seekable(self, *args, **kwargs): return self._stream.seekable(*args, **kwargs) def tell(self, *args, **kwargs): return self._stream.tell(*args, **kwargs) def truncate(self, *args, **kwargs): return self._stream.truncate(*args, **kwargs) def writable(self, *args, **kwargs): return self._stream.writable(*args, **kwargs) def writelines(self, *args, **kwargs): return self._stream.writelines(*args, **kwargs) # close is special because it will be called by __del__ but we do NOT # want to close the file unless we have to (we're just a wrapper). # Instead, we do nothing (we should be used through the decorator which # has its own mechanism to close the file correctly). def close(self, *args, **kwargs): pass
class _FileStream(io.IOBase): ''' Proxy around things that represent a file and need to be used as streams which may or not need to be closed. This will handle `pathlib.Path`, `str` paths, in-memory `bytes`, and anything IO-like (including `aiofiles`). It also provides access to the name and file size (also necessary). ''' def __init__(self, file, *, file_size=None): pass async def __aenter__(self): pass async def __aexit__(self, exc_type, exc_val, exc_tb): pass @property def file_size(self): pass @property def name(self): pass def read(self, *args, **kwargs): pass def readinto(self, *args, **kwargs): pass def write(self, *args, **kwargs): pass def fileno(self, *args, **kwargs): pass def flush(self, *args, **kwargs): pass def isatty(self, *args, **kwargs): pass def readable(self, *args, **kwargs): pass def readline(self, *args, **kwargs): pass def readlines(self, *args, **kwargs): pass def seek(self, *args, **kwargs): pass def seekable(self, *args, **kwargs): pass def tell(self, *args, **kwargs): pass def truncate(self, *args, **kwargs): pass def writable(self, *args, **kwargs): pass def writelines(self, *args, **kwargs): pass def close(self, *args, **kwargs): pass
24
1
4
0
3
0
1
0.17
1
4
0
0
21
5
21
41
99
16
71
32
62
12
80
30
58
7
4
2
29
146,735
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/helpers.py
telethon.helpers.TotalList
class TotalList(list): """ A list with an extra `total` property, which may not match its `len` since the total represents the total amount of items *available* somewhere else, not the items *in this list*. Examples: .. code-block:: python # Telethon returns these lists in some cases (for example, # only when a chunk is returned, but the "total" count # is available). result = await client.get_messages(chat, limit=10) print(result.total) # large number print(len(result)) # 10 print(result[0]) # latest message for x in result: # show the 10 messages print(x.text) """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.total = 0 def __str__(self): return '[{}, total={}]'.format( ', '.join(str(x) for x in self), self.total) def __repr__(self): return '[{}, total={}]'.format( ', '.join(repr(x) for x in self), self.total)
class TotalList(list): ''' A list with an extra `total` property, which may not match its `len` since the total represents the total amount of items *available* somewhere else, not the items *in this list*. Examples: .. code-block:: python # Telethon returns these lists in some cases (for example, # only when a chunk is returned, but the "total" count # is available). result = await client.get_messages(chat, limit=10) print(result.total) # large number print(len(result)) # 10 print(result[0]) # latest message for x in result: # show the 10 messages print(x.text) ''' def __init__(self, *args, **kwargs): pass def __str__(self): pass def __repr__(self): pass
4
1
3
0
3
0
1
1.6
1
2
0
0
3
1
3
36
34
8
10
5
6
16
8
5
4
1
2
0
3
146,736
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/network/connection/tcpobfuscated.py
telethon.network.connection.tcpobfuscated.ConnectionTcpObfuscated
class ConnectionTcpObfuscated(ObfuscatedConnection): """ Mode that Telegram defines as "obfuscated2". Encodes the packet just like `ConnectionTcpAbridged`, but encrypts every message with a randomly generated key using the AES-CTR mode so the packets are harder to discern. """ obfuscated_io = ObfuscatedIO packet_codec = AbridgedPacketCodec
class ConnectionTcpObfuscated(ObfuscatedConnection): ''' Mode that Telegram defines as "obfuscated2". Encodes the packet just like `ConnectionTcpAbridged`, but encrypts every message with a randomly generated key using the AES-CTR mode so the packets are harder to discern. '''
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
38
9
0
3
3
2
6
3
3
2
0
6
0
0
146,737
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/common.py
telethon.errors.common.MultiError
class MultiError(Exception): """Exception container for multiple `TLRequest`'s.""" def __new__(cls, exceptions, result, requests): if len(result) != len(exceptions) != len(requests): raise ValueError( 'Need result, exception and request for each error') for e, req in zip(exceptions, requests): if not isinstance(e, BaseException) and e is not None: raise TypeError( "Expected an exception object, not '%r'" % e ) if not isinstance(req, TLRequest): raise TypeError( "Expected TLRequest object, not '%r'" % req ) if len(exceptions) == 1: return exceptions[0] self = BaseException.__new__(cls) self.exceptions = list(exceptions) self.results = list(result) self.requests = list(requests) return self
class MultiError(Exception): '''Exception container for multiple `TLRequest`'s.''' def __new__(cls, exceptions, result, requests): pass
2
1
21
1
20
0
6
0.05
1
5
1
0
1
0
1
11
24
2
21
4
19
1
16
4
14
6
3
2
6
146,738
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/telegrambaseclient.py
telethon.client.telegrambaseclient._ExportState
class _ExportState: def __init__(self): # ``n`` is the amount of borrows a given sender has; # once ``n`` reaches ``0``, disconnect the sender after a while. self._n = 0 self._zero_ts = 0 self._connected = False def add_borrow(self): self._n += 1 self._connected = True def add_return(self): self._n -= 1 assert self._n >= 0, 'returned sender more than it was borrowed' if self._n == 0: self._zero_ts = time.time() def should_disconnect(self): return (self._n == 0 and self._connected and (time.time() - self._zero_ts) > _DISCONNECT_EXPORTED_AFTER) def need_connect(self): return not self._connected def mark_disconnected(self): assert self.should_disconnect(), 'marked as disconnected when it was borrowed' self._connected = False
class _ExportState: def __init__(self): pass def add_borrow(self): pass def add_return(self): pass def should_disconnect(self): pass def need_connect(self): pass def mark_disconnected(self): pass
7
0
4
0
4
0
1
0.09
0
0
0
0
6
3
6
6
29
5
22
10
15
2
20
10
13
2
0
1
7
146,739
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/errors/common.py
telethon.errors.common.InvalidBufferError
class InvalidBufferError(BufferError): """ Occurs when the buffer is invalid, and may contain an HTTP error code. For instance, 404 means "forgotten/broken authorization key", while """ def __init__(self, payload): self.payload = payload if len(payload) == 4: self.code = -struct.unpack('<i', payload)[0] super().__init__( 'Invalid response buffer (HTTP code {})'.format(self.code)) else: self.code = None super().__init__( 'Invalid response buffer (too short {})'.format(self.payload))
class InvalidBufferError(BufferError): ''' Occurs when the buffer is invalid, and may contain an HTTP error code. For instance, 404 means "forgotten/broken authorization key", while ''' def __init__(self, payload): pass
2
1
10
0
10
0
2
0.36
1
1
0
0
1
2
1
12
15
0
11
4
9
4
8
4
6
2
4
1
2
146,740
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/chats.py
telethon.client.chats._ChatAction
class _ChatAction: _str_mapping = { 'typing': types.SendMessageTypingAction(), 'contact': types.SendMessageChooseContactAction(), 'game': types.SendMessageGamePlayAction(), 'location': types.SendMessageGeoLocationAction(), 'sticker': types.SendMessageChooseStickerAction(), 'record-audio': types.SendMessageRecordAudioAction(), 'record-voice': types.SendMessageRecordAudioAction(), # alias 'record-round': types.SendMessageRecordRoundAction(), 'record-video': types.SendMessageRecordVideoAction(), 'audio': types.SendMessageUploadAudioAction(1), 'voice': types.SendMessageUploadAudioAction(1), # alias 'song': types.SendMessageUploadAudioAction(1), # alias 'round': types.SendMessageUploadRoundAction(1), 'video': types.SendMessageUploadVideoAction(1), 'photo': types.SendMessageUploadPhotoAction(1), 'document': types.SendMessageUploadDocumentAction(1), 'file': types.SendMessageUploadDocumentAction(1), # alias 'cancel': types.SendMessageCancelAction() } def __init__(self, client, chat, action, *, delay, auto_cancel): self._client = client self._chat = chat self._action = action self._delay = delay self._auto_cancel = auto_cancel self._request = None self._task = None self._running = False async def __aenter__(self): self._chat = await self._client.get_input_entity(self._chat) # Since `self._action` is passed by reference we can avoid # recreating the request all the time and still modify # `self._action.progress` directly in `progress`. self._request = functions.messages.SetTypingRequest( self._chat, self._action) self._running = True self._task = self._client.loop.create_task(self._update()) return self async def __aexit__(self, *args): self._running = False if self._task: self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._task = None __enter__ = helpers._sync_enter __exit__ = helpers._sync_exit async def _update(self): try: while self._running: await self._client(self._request) await asyncio.sleep(self._delay) except ConnectionError: pass except asyncio.CancelledError: if self._auto_cancel: await self._client(functions.messages.SetTypingRequest( self._chat, types.SendMessageCancelAction())) def progress(self, current, total): if hasattr(self._action, 'progress'): self._action.progress = 100 * round(current / total)
class _ChatAction: def __init__(self, client, chat, action, *, delay, auto_cancel): pass async def __aenter__(self): pass async def __aexit__(self, *args): pass async def _update(self): pass def progress(self, current, total): pass
6
0
9
1
8
1
2
0.11
0
1
0
0
5
8
5
5
78
13
62
17
56
7
41
17
35
5
0
2
12
146,741
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/chats.py
telethon.client.chats._AdminLogIter
class _AdminLogIter(RequestIter): async def _init( self, entity, admins, search, min_id, max_id, join, leave, invite, restrict, unrestrict, ban, unban, promote, demote, info, settings, pinned, edit, delete, group_call ): if any((join, leave, invite, restrict, unrestrict, ban, unban, promote, demote, info, settings, pinned, edit, delete, group_call)): events_filter = types.ChannelAdminLogEventsFilter( join=join, leave=leave, invite=invite, ban=restrict, unban=unrestrict, kick=ban, unkick=unban, promote=promote, demote=demote, info=info, settings=settings, pinned=pinned, edit=edit, delete=delete, group_call=group_call ) else: events_filter = None self.entity = await self.client.get_input_entity(entity) admin_list = [] if admins: if not utils.is_list_like(admins): admins = (admins,) for admin in admins: admin_list.append(await self.client.get_input_entity(admin)) self.request = functions.channels.GetAdminLogRequest( self.entity, q=search or '', min_id=min_id, max_id=max_id, limit=0, events_filter=events_filter, admins=admin_list or None ) async def _load_next_chunk(self): self.request.limit = min(self.left, _MAX_ADMIN_LOG_CHUNK_SIZE) r = await self.client(self.request) entities = {utils.get_peer_id(x): x for x in itertools.chain(r.users, r.chats)} self.request.max_id = min((e.id for e in r.events), default=0) for ev in r.events: if isinstance(ev.action, types.ChannelAdminLogEventActionEditMessage): ev.action.prev_message._finish_init( self.client, entities, self.entity) ev.action.new_message._finish_init( self.client, entities, self.entity) elif isinstance(ev.action, types.ChannelAdminLogEventActionDeleteMessage): ev.action.message._finish_init( self.client, entities, self.entity) self.buffer.append(custom.AdminLogEvent(ev, entities)) if len(r.events) < self.request.limit: return True
class _AdminLogIter(RequestIter): async def _init( self, entity, admins, search, min_id, max_id, join, leave, invite, restrict, unrestrict, ban, unban, promote, demote, info, settings, pinned, edit, delete, group_call ): pass async def _load_next_chunk(self): pass
3
0
29
5
24
0
5
0
1
1
0
0
2
2
2
31
59
10
49
16
41
0
26
11
23
5
5
2
10
146,742
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/chats.py
telethon.client.chats.ChatMethods
class ChatMethods: # region Public methods def iter_participants( self: 'TelegramClient', entity: 'hints.EntityLike', limit: float = None, *, search: str = '', filter: 'types.TypeChannelParticipantsFilter' = None, aggressive: bool = False) -> _ParticipantsIter: """ Iterator over the participants belonging to the specified chat. The order is unspecified. Arguments entity (`entity`): The entity from which to retrieve the participants list. limit (`int`): Limits amount of participants fetched. search (`str`, optional): Look for participants with this string in name/username. filter (:tl:`ChannelParticipantsFilter`, optional): The filter to be used, if you want e.g. only admins Note that you might not have permissions for some filter. This has no effect for normal chats or users. .. note:: The filter :tl:`ChannelParticipantsBanned` will return *restricted* users. If you want *banned* users you should use :tl:`ChannelParticipantsKicked` instead. aggressive (`bool`, optional): Does nothing. This is kept for backwards-compatibility. There have been several changes to Telegram's API that limits the amount of members that can be retrieved, and this was a hack that no longer works. Yields The :tl:`User` objects returned by :tl:`GetParticipantsRequest` with an additional ``.participant`` attribute which is the matched :tl:`ChannelParticipant` type for channels/megagroups or :tl:`ChatParticipants` for normal chats. Example .. code-block:: python # Show all user IDs in a chat async for user in client.iter_participants(chat): print(user.id) # Search by name async for user in client.iter_participants(chat, search='name'): print(user.username) # Filter by admins from telethon.tl.types import ChannelParticipantsAdmins async for user in client.iter_participants(chat, filter=ChannelParticipantsAdmins): print(user.first_name) """ return _ParticipantsIter( self, limit, entity=entity, filter=filter, search=search ) async def get_participants( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': """ Same as `iter_participants()`, but returns a `TotalList <telethon.helpers.TotalList>` instead. Example .. code-block:: python users = await client.get_participants(chat) print(users[0].first_name) for user in users: if user.username is not None: print(user.username) """ return await self.iter_participants(*args, **kwargs).collect() get_participants.__signature__ = inspect.signature(iter_participants) def iter_admin_log( self: 'TelegramClient', entity: 'hints.EntityLike', limit: float = None, *, max_id: int = 0, min_id: int = 0, search: str = None, admins: 'hints.EntitiesLike' = None, join: bool = None, leave: bool = None, invite: bool = None, restrict: bool = None, unrestrict: bool = None, ban: bool = None, unban: bool = None, promote: bool = None, demote: bool = None, info: bool = None, settings: bool = None, pinned: bool = None, edit: bool = None, delete: bool = None, group_call: bool = None) -> _AdminLogIter: """ Iterator over the admin log for the specified channel. The default order is from the most recent event to to the oldest. Note that you must be an administrator of it to use this method. If none of the filters are present (i.e. they all are `None`), *all* event types will be returned. If at least one of them is `True`, only those that are true will be returned. Arguments entity (`entity`): The channel entity from which to get its admin log. limit (`int` | `None`, optional): Number of events to be retrieved. The limit may also be `None`, which would eventually return the whole history. max_id (`int`): All the events with a higher (newer) ID or equal to this will be excluded. min_id (`int`): All the events with a lower (older) ID or equal to this will be excluded. search (`str`): The string to be used as a search query. admins (`entity` | `list`): If present, the events will be filtered by these admins (or single admin) and only those caused by them will be returned. join (`bool`): If `True`, events for when a user joined will be returned. leave (`bool`): If `True`, events for when a user leaves will be returned. invite (`bool`): If `True`, events for when a user joins through an invite link will be returned. restrict (`bool`): If `True`, events with partial restrictions will be returned. This is what the API calls "ban". unrestrict (`bool`): If `True`, events removing restrictions will be returned. This is what the API calls "unban". ban (`bool`): If `True`, events applying or removing all restrictions will be returned. This is what the API calls "kick" (restricting all permissions removed is a ban, which kicks the user). unban (`bool`): If `True`, events removing all restrictions will be returned. This is what the API calls "unkick". promote (`bool`): If `True`, events with admin promotions will be returned. demote (`bool`): If `True`, events with admin demotions will be returned. info (`bool`): If `True`, events changing the group info will be returned. settings (`bool`): If `True`, events changing the group settings will be returned. pinned (`bool`): If `True`, events of new pinned messages will be returned. edit (`bool`): If `True`, events of message edits will be returned. delete (`bool`): If `True`, events of message deletions will be returned. group_call (`bool`): If `True`, events related to group calls will be returned. Yields Instances of `AdminLogEvent <telethon.tl.custom.adminlogevent.AdminLogEvent>`. Example .. code-block:: python async for event in client.iter_admin_log(channel): if event.changed_title: print('The title changed from', event.old, 'to', event.new) """ return _AdminLogIter( self, limit, entity=entity, admins=admins, search=search, min_id=min_id, max_id=max_id, join=join, leave=leave, invite=invite, restrict=restrict, unrestrict=unrestrict, ban=ban, unban=unban, promote=promote, demote=demote, info=info, settings=settings, pinned=pinned, edit=edit, delete=delete, group_call=group_call ) async def get_admin_log( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': """ Same as `iter_admin_log()`, but returns a ``list`` instead. Example .. code-block:: python # Get a list of deleted message events which said "heck" events = await client.get_admin_log(channel, search='heck', delete=True) # Print the old message before it was deleted print(events[0].old) """ return await self.iter_admin_log(*args, **kwargs).collect() get_admin_log.__signature__ = inspect.signature(iter_admin_log) def iter_profile_photos( self: 'TelegramClient', entity: 'hints.EntityLike', limit: int = None, *, offset: int = 0, max_id: int = 0) -> _ProfilePhotoIter: """ Iterator over a user's profile photos or a chat's photos. The order is from the most recent photo to the oldest. Arguments entity (`entity`): The entity from which to get the profile or chat photos. limit (`int` | `None`, optional): Number of photos to be retrieved. The limit may also be `None`, which would eventually all the photos that are still available. offset (`int`): How many photos should be skipped before returning the first one. max_id (`int`): The maximum ID allowed when fetching photos. Yields Instances of :tl:`Photo`. Example .. code-block:: python # Download all the profile photos of some user async for photo in client.iter_profile_photos(user): await client.download_media(photo) """ return _ProfilePhotoIter( self, limit, entity=entity, offset=offset, max_id=max_id ) async def get_profile_photos( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': """ Same as `iter_profile_photos()`, but returns a `TotalList <telethon.helpers.TotalList>` instead. Example .. code-block:: python # Get the photos of a channel photos = await client.get_profile_photos(channel) # Download the oldest photo await client.download_media(photos[-1]) """ return await self.iter_profile_photos(*args, **kwargs).collect() get_profile_photos.__signature__ = inspect.signature(iter_profile_photos) def action( self: 'TelegramClient', entity: 'hints.EntityLike', action: 'typing.Union[str, types.TypeSendMessageAction]', *, delay: float = 4, auto_cancel: bool = True) -> 'typing.Union[_ChatAction, typing.Coroutine]': """ Returns a context-manager object to represent a "chat action". Chat actions indicate things like "user is typing", "user is uploading a photo", etc. If the action is ``'cancel'``, you should just ``await`` the result, since it makes no sense to use a context-manager for it. See the example below for intended usage. Arguments entity (`entity`): The entity where the action should be showed in. action (`str` | :tl:`SendMessageAction`): The action to show. You can either pass a instance of :tl:`SendMessageAction` or better, a string used while: * ``'typing'``: typing a text message. * ``'contact'``: choosing a contact. * ``'game'``: playing a game. * ``'location'``: choosing a geo location. * ``'sticker'``: choosing a sticker. * ``'record-audio'``: recording a voice note. You may use ``'record-voice'`` as alias. * ``'record-round'``: recording a round video. * ``'record-video'``: recording a normal video. * ``'audio'``: sending an audio file (voice note or song). You may use ``'voice'`` and ``'song'`` as aliases. * ``'round'``: uploading a round video. * ``'video'``: uploading a video file. * ``'photo'``: uploading a photo. * ``'document'``: uploading a document file. You may use ``'file'`` as alias. * ``'cancel'``: cancel any pending action in this chat. Invalid strings will raise a ``ValueError``. delay (`int` | `float`): The delay, in seconds, to wait between sending actions. For example, if the delay is 5 and it takes 7 seconds to do something, three requests will be made at 0s, 5s, and 7s to cancel the action. auto_cancel (`bool`): Whether the action should be cancelled once the context manager exists or not. The default is `True`, since you don't want progress to be shown when it has already completed. Returns Either a context-manager object or a coroutine. Example .. code-block:: python # Type for 2 seconds, then send a message async with client.action(chat, 'typing'): await asyncio.sleep(2) await client.send_message(chat, 'Hello world! I type slow ^^') # Cancel any previous action await client.action(chat, 'cancel') # Upload a document, showing its progress (most clients ignore this) async with client.action(chat, 'document') as action: await client.send_file(chat, zip_file, progress_callback=action.progress) """ if isinstance(action, str): try: action = _ChatAction._str_mapping[action.lower()] except KeyError: raise ValueError( 'No such action "{}"'.format(action)) from None elif not isinstance(action, types.TLObject) or action.SUBCLASS_OF_ID != 0x20b2cc21: # 0x20b2cc21 = crc32(b'SendMessageAction') if isinstance(action, type): raise ValueError('You must pass an instance, not the class') else: raise ValueError('Cannot use {} as action'.format(action)) if isinstance(action, types.SendMessageCancelAction): # ``SetTypingRequest.resolve`` will get input peer of ``entity``. return self(functions.messages.SetTypingRequest( entity, types.SendMessageCancelAction())) return _ChatAction( self, entity, action, delay=delay, auto_cancel=auto_cancel) async def edit_admin( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'hints.EntityLike', *, change_info: bool = None, post_messages: bool = None, edit_messages: bool = None, delete_messages: bool = None, ban_users: bool = None, invite_users: bool = None, pin_messages: bool = None, add_admins: bool = None, manage_call: bool = None, anonymous: bool = None, is_admin: bool = None, title: str = None) -> types.Updates: """ Edits admin permissions for someone in a chat. Raises an error if a wrong combination of rights are given (e.g. you don't have enough permissions to grant one). Unless otherwise stated, permissions will work in channels and megagroups. Arguments entity (`entity`): The channel, megagroup or chat where the promotion should happen. user (`entity`): The user to be promoted. change_info (`bool`, optional): Whether the user will be able to change info. post_messages (`bool`, optional): Whether the user will be able to post in the channel. This will only work in broadcast channels. edit_messages (`bool`, optional): Whether the user will be able to edit messages in the channel. This will only work in broadcast channels. delete_messages (`bool`, optional): Whether the user will be able to delete messages. ban_users (`bool`, optional): Whether the user will be able to ban users. invite_users (`bool`, optional): Whether the user will be able to invite users. Needs some testing. pin_messages (`bool`, optional): Whether the user will be able to pin messages. add_admins (`bool`, optional): Whether the user will be able to add admins. manage_call (`bool`, optional): Whether the user will be able to manage group calls. anonymous (`bool`, optional): Whether the user will remain anonymous when sending messages. The sender of the anonymous messages becomes the group itself. .. note:: Users may be able to identify the anonymous admin by its custom title, so additional care is needed when using both ``anonymous`` and custom titles. For example, if multiple anonymous admins share the same title, users won't be able to distinguish them. is_admin (`bool`, optional): Whether the user will be an admin in the chat. This will only work in small group chats. Whether the user will be an admin in the chat. This is the only permission available in small group chats, and when used in megagroups, all non-explicitly set permissions will have this value. Essentially, only passing ``is_admin=True`` will grant all permissions, but you can still disable those you need. title (`str`, optional): The custom title (also known as "rank") to show for this admin. This text will be shown instead of the "admin" badge. This will only work in channels and megagroups. When left unspecified or empty, the default localized "admin" badge will be shown. Returns The resulting :tl:`Updates` object. Example .. code-block:: python # Allowing `user` to pin messages in `chat` await client.edit_admin(chat, user, pin_messages=True) # Granting all permissions except for `add_admins` await client.edit_admin(chat, user, is_admin=True, add_admins=False) """ entity = await self.get_input_entity(entity) user = await self.get_input_entity(user) perm_names = ( 'change_info', 'post_messages', 'edit_messages', 'delete_messages', 'ban_users', 'invite_users', 'pin_messages', 'add_admins', 'anonymous', 'manage_call', ) ty = helpers._entity_type(entity) if ty == helpers._EntityType.CHANNEL: # If we try to set these permissions in a megagroup, we # would get a RIGHT_FORBIDDEN. However, it makes sense # that an admin can post messages, so we want to avoid the error if post_messages or edit_messages: # TODO get rid of this once sessions cache this information if entity.channel_id not in self._megagroup_cache: full_entity = await self.get_entity(entity) self._megagroup_cache[entity.channel_id] = full_entity.megagroup if self._megagroup_cache[entity.channel_id]: post_messages = None edit_messages = None perms = locals() return await self(functions.channels.EditAdminRequest(entity, user, types.ChatAdminRights(**{ # A permission is its explicit (not-None) value or `is_admin`. # This essentially makes `is_admin` be the default value. name: perms[name] if perms[name] is not None else is_admin for name in perm_names }), rank=title or '')) elif ty == helpers._EntityType.CHAT: # If the user passed any permission in a small # group chat, they must be a full admin to have it. if is_admin is None: is_admin = any(locals()[x] for x in perm_names) return await self(functions.messages.EditChatAdminRequest( entity.chat_id, user, is_admin=is_admin)) else: raise ValueError( 'You can only edit permissions in groups and channels') async def edit_permissions( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'typing.Optional[hints.EntityLike]' = None, until_date: 'hints.DateLike' = None, *, view_messages: bool = True, send_messages: bool = True, send_media: bool = True, send_stickers: bool = True, send_gifs: bool = True, send_games: bool = True, send_inline: bool = True, embed_link_previews: bool = True, send_polls: bool = True, change_info: bool = True, invite_users: bool = True, pin_messages: bool = True) -> types.Updates: """ Edits user restrictions in a chat. Set an argument to `False` to apply a restriction (i.e. remove the permission), or omit them to use the default `True` (i.e. don't apply a restriction). Raises an error if a wrong combination of rights are given (e.g. you don't have enough permissions to revoke one). By default, each boolean argument is `True`, meaning that it is true that the user has access to the default permission and may be able to make use of it. If you set an argument to `False`, then a restriction is applied regardless of the default permissions. It is important to note that `True` does *not* mean grant, only "don't restrict", and this is where the default permissions come in. A user may have not been revoked the ``pin_messages`` permission (it is `True`) but they won't be able to use it if the default permissions don't allow it either. Arguments entity (`entity`): The channel or megagroup where the restriction should happen. user (`entity`, optional): If specified, the permission will be changed for the specific user. If left as `None`, the default chat permissions will be updated. until_date (`DateLike`, optional): When the user will be unbanned. If the due date or duration is longer than 366 days or shorter than 30 seconds, the ban will be forever. Defaults to ``0`` (ban forever). view_messages (`bool`, optional): Whether the user is able to view messages or not. Forbidding someone from viewing messages equals to banning them. This will only work if ``user`` is set. send_messages (`bool`, optional): Whether the user is able to send messages or not. send_media (`bool`, optional): Whether the user is able to send media or not. send_stickers (`bool`, optional): Whether the user is able to send stickers or not. send_gifs (`bool`, optional): Whether the user is able to send animated gifs or not. send_games (`bool`, optional): Whether the user is able to send games or not. send_inline (`bool`, optional): Whether the user is able to use inline bots or not. embed_link_previews (`bool`, optional): Whether the user is able to enable the link preview in the messages they send. Note that the user will still be able to send messages with links if this permission is removed, but these links won't display a link preview. send_polls (`bool`, optional): Whether the user is able to send polls or not. change_info (`bool`, optional): Whether the user is able to change info or not. invite_users (`bool`, optional): Whether the user is able to invite other users or not. pin_messages (`bool`, optional): Whether the user is able to pin messages or not. Returns The resulting :tl:`Updates` object. Example .. code-block:: python from datetime import timedelta # Banning `user` from `chat` for 1 minute await client.edit_permissions(chat, user, timedelta(minutes=1), view_messages=False) # Banning `user` from `chat` forever await client.edit_permissions(chat, user, view_messages=False) # Kicking someone (ban + un-ban) await client.edit_permissions(chat, user, view_messages=False) await client.edit_permissions(chat, user) """ entity = await self.get_input_entity(entity) ty = helpers._entity_type(entity) if ty != helpers._EntityType.CHANNEL: raise ValueError('You must pass either a channel or a supergroup') rights = types.ChatBannedRights( until_date=until_date, view_messages=not view_messages, send_messages=not send_messages, send_media=not send_media, send_stickers=not send_stickers, send_gifs=not send_gifs, send_games=not send_games, send_inline=not send_inline, embed_links=not embed_link_previews, send_polls=not send_polls, change_info=not change_info, invite_users=not invite_users, pin_messages=not pin_messages ) if user is None: return await self(functions.messages.EditChatDefaultBannedRightsRequest( peer=entity, banned_rights=rights )) user = await self.get_input_entity(user) return await self(functions.channels.EditBannedRequest( channel=entity, participant=user, banned_rights=rights )) async def kick_participant( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'typing.Optional[hints.EntityLike]' ): """ Kicks a user from a chat. Kicking yourself (``'me'``) will result in leaving the chat. .. note:: Attempting to kick someone who was banned will remove their restrictions (and thus unbanning them), since kicking is just ban + unban. Arguments entity (`entity`): The channel or chat where the user should be kicked from. user (`entity`, optional): The user to kick. Returns Returns the service `Message <telethon.tl.custom.message.Message>` produced about a user being kicked, if any. Example .. code-block:: python # Kick some user from some chat, and deleting the service message msg = await client.kick_participant(chat, user) await msg.delete() # Leaving chat await client.kick_participant(chat, 'me') """ entity = await self.get_input_entity(entity) user = await self.get_input_entity(user) ty = helpers._entity_type(entity) if ty == helpers._EntityType.CHAT: resp = await self(functions.messages.DeleteChatUserRequest(entity.chat_id, user)) elif ty == helpers._EntityType.CHANNEL: if isinstance(user, types.InputPeerSelf): # Despite no longer being in the channel, the account still # seems to get the service message. resp = await self(functions.channels.LeaveChannelRequest(entity)) else: resp = await self(functions.channels.EditBannedRequest( channel=entity, participant=user, banned_rights=types.ChatBannedRights( until_date=None, view_messages=True) )) await asyncio.sleep(0.5) await self(functions.channels.EditBannedRequest( channel=entity, participant=user, banned_rights=types.ChatBannedRights(until_date=None) )) else: raise ValueError('You must pass either a channel or a chat') return self._get_response_message(None, resp, entity) async def get_permissions( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'hints.EntityLike' = None ) -> 'typing.Optional[custom.ParticipantPermissions]': """ Fetches the permissions of a user in a specific chat or channel or get Default Restricted Rights of Chat or Channel. .. note:: This request has to fetch the entire chat for small group chats, which can get somewhat expensive, so use of a cache is advised. Arguments entity (`entity`): The channel or chat the user is participant of. user (`entity`, optional): Target user. Returns A `ParticipantPermissions <telethon.tl.custom.participantpermissions.ParticipantPermissions>` instance. Refer to its documentation to see what properties are available. Example .. code-block:: python permissions = await client.get_permissions(chat, user) if permissions.is_admin: # do something # Get Banned Permissions of Chat await client.get_permissions(chat) """ entity = await self.get_entity(entity) if not user: if isinstance(entity, types.Channel): FullChat = await self(functions.channels.GetFullChannelRequest(entity)) elif isinstance(entity, types.Chat): FullChat = await self(functions.messages.GetFullChatRequest(entity.id)) else: return return FullChat.chats[0].default_banned_rights entity = await self.get_input_entity(entity) user = await self.get_input_entity(user) if helpers._entity_type(entity) == helpers._EntityType.CHANNEL: participant = await self(functions.channels.GetParticipantRequest( entity, user )) return custom.ParticipantPermissions(participant.participant, False) elif helpers._entity_type(entity) == helpers._EntityType.CHAT: chat = await self(functions.messages.GetFullChatRequest( entity.chat_id )) if isinstance(user, types.InputPeerSelf): user = await self.get_me(input_peer=True) for participant in chat.full_chat.participants.participants: if participant.user_id == user.user_id: return custom.ParticipantPermissions(participant, True) raise errors.UserNotParticipantError(None) raise ValueError('You must pass either a channel or a chat') async def get_stats( self: 'TelegramClient', entity: 'hints.EntityLike', message: 'typing.Union[int, types.Message]' = None, ): """ Retrieves statistics from the given megagroup or broadcast channel. Note that some restrictions apply before being able to fetch statistics, in particular the channel must have enough members (for megagroups, this requires `at least 500 members`_). Arguments entity (`entity`): The channel from which to get statistics. message (`int` | ``Message``, optional): The message ID from which to get statistics, if your goal is to obtain the statistics of a single message. Raises If the given entity is not a channel (broadcast or megagroup), a `TypeError` is raised. If there are not enough members (poorly named) errors such as ``telethon.errors.ChatAdminRequiredError`` will appear. Returns If both ``entity`` and ``message`` were provided, returns :tl:`MessageStats`. Otherwise, either :tl:`BroadcastStats` or :tl:`MegagroupStats`, depending on whether the input belonged to a broadcast channel or megagroup. Example .. code-block:: python # Some megagroup or channel username or ID to fetch channel = -100123 stats = await client.get_stats(channel) print('Stats from', stats.period.min_date, 'to', stats.period.max_date, ':') print(stats.stringify()) .. _`at least 500 members`: https://telegram.org/blog/profile-videos-people-nearby-and-more """ entity = await self.get_input_entity(entity) if helpers._entity_type(entity) != helpers._EntityType.CHANNEL: raise TypeError('You must pass a channel entity') message = utils.get_message_id(message) if message is not None: try: req = functions.stats.GetMessageStatsRequest(entity, message) return await self(req) except errors.StatsMigrateError as e: dc = e.dc else: # Don't bother fetching the Channel entity (costs a request), instead # try to guess and if it fails we know it's the other one (best case # no extra request, worst just one). try: req = functions.stats.GetBroadcastStatsRequest(entity) return await self(req) except errors.StatsMigrateError as e: dc = e.dc except errors.BroadcastRequiredError: req = functions.stats.GetMegagroupStatsRequest(entity) try: return await self(req) except errors.StatsMigrateError as e: dc = e.dc sender = await self._borrow_exported_sender(dc) try: # req will be resolved to use the right types inside by now return await sender.send(req) finally: await self._return_exported_sender(sender)
class ChatMethods: def iter_participants( self: 'TelegramClient', entity: 'hints.EntityLike', limit: float = None, *, search: str = '', filter: 'types.TypeChannelParticipantsFilter' = None, aggressive: bool = False) -> _ParticipantsIter: ''' Iterator over the participants belonging to the specified chat. The order is unspecified. Arguments entity (`entity`): The entity from which to retrieve the participants list. limit (`int`): Limits amount of participants fetched. search (`str`, optional): Look for participants with this string in name/username. filter (:tl:`ChannelParticipantsFilter`, optional): The filter to be used, if you want e.g. only admins Note that you might not have permissions for some filter. This has no effect for normal chats or users. .. note:: The filter :tl:`ChannelParticipantsBanned` will return *restricted* users. If you want *banned* users you should use :tl:`ChannelParticipantsKicked` instead. aggressive (`bool`, optional): Does nothing. This is kept for backwards-compatibility. There have been several changes to Telegram's API that limits the amount of members that can be retrieved, and this was a hack that no longer works. Yields The :tl:`User` objects returned by :tl:`GetParticipantsRequest` with an additional ``.participant`` attribute which is the matched :tl:`ChannelParticipant` type for channels/megagroups or :tl:`ChatParticipants` for normal chats. Example .. code-block:: python # Show all user IDs in a chat async for user in client.iter_participants(chat): print(user.id) # Search by name async for user in client.iter_participants(chat, search='name'): print(user.username) # Filter by admins from telethon.tl.types import ChannelParticipantsAdmins async for user in client.iter_participants(chat, filter=ChannelParticipantsAdmins): print(user.first_name) ''' pass async def get_participants( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': ''' Same as `iter_participants()`, but returns a `TotalList <telethon.helpers.TotalList>` instead. Example .. code-block:: python users = await client.get_participants(chat) print(users[0].first_name) for user in users: if user.username is not None: print(user.username) ''' pass def iter_admin_log( self: 'TelegramClient', entity: 'hints.EntityLike', limit: float = None, *, max_id: int = 0, min_id: int = 0, search: str = None, admins: 'hints.EntitiesLike' = None, join: bool = None, leave: bool = None, invite: bool = None, restrict: bool = None, unrestrict: bool = None, ban: bool = None, unban: bool = None, promote: bool = None, demote: bool = None, info: bool = None, settings: bool = None, pinned: bool = None, edit: bool = None, delete: bool = None, group_call: bool = None) -> _AdminLogIter: ''' Iterator over the admin log for the specified channel. The default order is from the most recent event to to the oldest. Note that you must be an administrator of it to use this method. If none of the filters are present (i.e. they all are `None`), *all* event types will be returned. If at least one of them is `True`, only those that are true will be returned. Arguments entity (`entity`): The channel entity from which to get its admin log. limit (`int` | `None`, optional): Number of events to be retrieved. The limit may also be `None`, which would eventually return the whole history. max_id (`int`): All the events with a higher (newer) ID or equal to this will be excluded. min_id (`int`): All the events with a lower (older) ID or equal to this will be excluded. search (`str`): The string to be used as a search query. admins (`entity` | `list`): If present, the events will be filtered by these admins (or single admin) and only those caused by them will be returned. join (`bool`): If `True`, events for when a user joined will be returned. leave (`bool`): If `True`, events for when a user leaves will be returned. invite (`bool`): If `True`, events for when a user joins through an invite link will be returned. restrict (`bool`): If `True`, events with partial restrictions will be returned. This is what the API calls "ban". unrestrict (`bool`): If `True`, events removing restrictions will be returned. This is what the API calls "unban". ban (`bool`): If `True`, events applying or removing all restrictions will be returned. This is what the API calls "kick" (restricting all permissions removed is a ban, which kicks the user). unban (`bool`): If `True`, events removing all restrictions will be returned. This is what the API calls "unkick". promote (`bool`): If `True`, events with admin promotions will be returned. demote (`bool`): If `True`, events with admin demotions will be returned. info (`bool`): If `True`, events changing the group info will be returned. settings (`bool`): If `True`, events changing the group settings will be returned. pinned (`bool`): If `True`, events of new pinned messages will be returned. edit (`bool`): If `True`, events of message edits will be returned. delete (`bool`): If `True`, events of message deletions will be returned. group_call (`bool`): If `True`, events related to group calls will be returned. Yields Instances of `AdminLogEvent <telethon.tl.custom.adminlogevent.AdminLogEvent>`. Example .. code-block:: python async for event in client.iter_admin_log(channel): if event.changed_title: print('The title changed from', event.old, 'to', event.new) ''' pass async def get_admin_log( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': ''' Same as `iter_admin_log()`, but returns a ``list`` instead. Example .. code-block:: python # Get a list of deleted message events which said "heck" events = await client.get_admin_log(channel, search='heck', delete=True) # Print the old message before it was deleted print(events[0].old) ''' pass def iter_profile_photos( self: 'TelegramClient', entity: 'hints.EntityLike', limit: int = None, *, offset: int = 0, max_id: int = 0) -> _ProfilePhotoIter: ''' Iterator over a user's profile photos or a chat's photos. The order is from the most recent photo to the oldest. Arguments entity (`entity`): The entity from which to get the profile or chat photos. limit (`int` | `None`, optional): Number of photos to be retrieved. The limit may also be `None`, which would eventually all the photos that are still available. offset (`int`): How many photos should be skipped before returning the first one. max_id (`int`): The maximum ID allowed when fetching photos. Yields Instances of :tl:`Photo`. Example .. code-block:: python # Download all the profile photos of some user async for photo in client.iter_profile_photos(user): await client.download_media(photo) ''' pass async def get_profile_photos( self: 'TelegramClient', *args, **kwargs) -> 'hints.TotalList': ''' Same as `iter_profile_photos()`, but returns a `TotalList <telethon.helpers.TotalList>` instead. Example .. code-block:: python # Get the photos of a channel photos = await client.get_profile_photos(channel) # Download the oldest photo await client.download_media(photos[-1]) ''' pass def action( self: 'TelegramClient', entity: 'hints.EntityLike', action: 'typing.Union[str, types.TypeSendMessageAction]', *, delay: float = 4, auto_cancel: bool = True) -> 'typing.Union[_ChatAction, typing.Coroutine]': ''' Returns a context-manager object to represent a "chat action". Chat actions indicate things like "user is typing", "user is uploading a photo", etc. If the action is ``'cancel'``, you should just ``await`` the result, since it makes no sense to use a context-manager for it. See the example below for intended usage. Arguments entity (`entity`): The entity where the action should be showed in. action (`str` | :tl:`SendMessageAction`): The action to show. You can either pass a instance of :tl:`SendMessageAction` or better, a string used while: * ``'typing'``: typing a text message. * ``'contact'``: choosing a contact. * ``'game'``: playing a game. * ``'location'``: choosing a geo location. * ``'sticker'``: choosing a sticker. * ``'record-audio'``: recording a voice note. You may use ``'record-voice'`` as alias. * ``'record-round'``: recording a round video. * ``'record-video'``: recording a normal video. * ``'audio'``: sending an audio file (voice note or song). You may use ``'voice'`` and ``'song'`` as aliases. * ``'round'``: uploading a round video. * ``'video'``: uploading a video file. * ``'photo'``: uploading a photo. * ``'document'``: uploading a document file. You may use ``'file'`` as alias. * ``'cancel'``: cancel any pending action in this chat. Invalid strings will raise a ``ValueError``. delay (`int` | `float`): The delay, in seconds, to wait between sending actions. For example, if the delay is 5 and it takes 7 seconds to do something, three requests will be made at 0s, 5s, and 7s to cancel the action. auto_cancel (`bool`): Whether the action should be cancelled once the context manager exists or not. The default is `True`, since you don't want progress to be shown when it has already completed. Returns Either a context-manager object or a coroutine. Example .. code-block:: python # Type for 2 seconds, then send a message async with client.action(chat, 'typing'): await asyncio.sleep(2) await client.send_message(chat, 'Hello world! I type slow ^^') # Cancel any previous action await client.action(chat, 'cancel') # Upload a document, showing its progress (most clients ignore this) async with client.action(chat, 'document') as action: await client.send_file(chat, zip_file, progress_callback=action.progress) ''' pass async def edit_admin( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'hints.EntityLike', *, change_info: bool = None, post_messages: bool = None, edit_messages: bool = None, delete_messages: bool = None, ban_users: bool = None, invite_users: bool = None, pin_messages: bool = None, add_admins: bool = None, manage_call: bool = None, anonymous: bool = None, is_admin: bool = None, title: str = None) -> types.Updates: ''' Edits admin permissions for someone in a chat. Raises an error if a wrong combination of rights are given (e.g. you don't have enough permissions to grant one). Unless otherwise stated, permissions will work in channels and megagroups. Arguments entity (`entity`): The channel, megagroup or chat where the promotion should happen. user (`entity`): The user to be promoted. change_info (`bool`, optional): Whether the user will be able to change info. post_messages (`bool`, optional): Whether the user will be able to post in the channel. This will only work in broadcast channels. edit_messages (`bool`, optional): Whether the user will be able to edit messages in the channel. This will only work in broadcast channels. delete_messages (`bool`, optional): Whether the user will be able to delete messages. ban_users (`bool`, optional): Whether the user will be able to ban users. invite_users (`bool`, optional): Whether the user will be able to invite users. Needs some testing. pin_messages (`bool`, optional): Whether the user will be able to pin messages. add_admins (`bool`, optional): Whether the user will be able to add admins. manage_call (`bool`, optional): Whether the user will be able to manage group calls. anonymous (`bool`, optional): Whether the user will remain anonymous when sending messages. The sender of the anonymous messages becomes the group itself. .. note:: Users may be able to identify the anonymous admin by its custom title, so additional care is needed when using both ``anonymous`` and custom titles. For example, if multiple anonymous admins share the same title, users won't be able to distinguish them. is_admin (`bool`, optional): Whether the user will be an admin in the chat. This will only work in small group chats. Whether the user will be an admin in the chat. This is the only permission available in small group chats, and when used in megagroups, all non-explicitly set permissions will have this value. Essentially, only passing ``is_admin=True`` will grant all permissions, but you can still disable those you need. title (`str`, optional): The custom title (also known as "rank") to show for this admin. This text will be shown instead of the "admin" badge. This will only work in channels and megagroups. When left unspecified or empty, the default localized "admin" badge will be shown. Returns The resulting :tl:`Updates` object. Example .. code-block:: python # Allowing `user` to pin messages in `chat` await client.edit_admin(chat, user, pin_messages=True) # Granting all permissions except for `add_admins` await client.edit_admin(chat, user, is_admin=True, add_admins=False) ''' pass async def edit_permissions( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'typing.Optional[hints.EntityLike]' = None, until_date: 'hints.DateLike' = None, *, view_messages: bool = True, send_messages: bool = True, send_media: bool = True, send_stickers: bool = True, send_gifs: bool = True, send_games: bool = True, send_inline: bool = True, embed_link_previews: bool = True, send_polls: bool = True, change_info: bool = True, invite_users: bool = True, pin_messages: bool = True) -> types.Updates: ''' Edits user restrictions in a chat. Set an argument to `False` to apply a restriction (i.e. remove the permission), or omit them to use the default `True` (i.e. don't apply a restriction). Raises an error if a wrong combination of rights are given (e.g. you don't have enough permissions to revoke one). By default, each boolean argument is `True`, meaning that it is true that the user has access to the default permission and may be able to make use of it. If you set an argument to `False`, then a restriction is applied regardless of the default permissions. It is important to note that `True` does *not* mean grant, only "don't restrict", and this is where the default permissions come in. A user may have not been revoked the ``pin_messages`` permission (it is `True`) but they won't be able to use it if the default permissions don't allow it either. Arguments entity (`entity`): The channel or megagroup where the restriction should happen. user (`entity`, optional): If specified, the permission will be changed for the specific user. If left as `None`, the default chat permissions will be updated. until_date (`DateLike`, optional): When the user will be unbanned. If the due date or duration is longer than 366 days or shorter than 30 seconds, the ban will be forever. Defaults to ``0`` (ban forever). view_messages (`bool`, optional): Whether the user is able to view messages or not. Forbidding someone from viewing messages equals to banning them. This will only work if ``user`` is set. send_messages (`bool`, optional): Whether the user is able to send messages or not. send_media (`bool`, optional): Whether the user is able to send media or not. send_stickers (`bool`, optional): Whether the user is able to send stickers or not. send_gifs (`bool`, optional): Whether the user is able to send animated gifs or not. send_games (`bool`, optional): Whether the user is able to send games or not. send_inline (`bool`, optional): Whether the user is able to use inline bots or not. embed_link_previews (`bool`, optional): Whether the user is able to enable the link preview in the messages they send. Note that the user will still be able to send messages with links if this permission is removed, but these links won't display a link preview. send_polls (`bool`, optional): Whether the user is able to send polls or not. change_info (`bool`, optional): Whether the user is able to change info or not. invite_users (`bool`, optional): Whether the user is able to invite other users or not. pin_messages (`bool`, optional): Whether the user is able to pin messages or not. Returns The resulting :tl:`Updates` object. Example .. code-block:: python from datetime import timedelta # Banning `user` from `chat` for 1 minute await client.edit_permissions(chat, user, timedelta(minutes=1), view_messages=False) # Banning `user` from `chat` forever await client.edit_permissions(chat, user, view_messages=False) # Kicking someone (ban + un-ban) await client.edit_permissions(chat, user, view_messages=False) await client.edit_permissions(chat, user) ''' pass async def kick_participant( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'typing.Optional[hints.EntityLike]' ): ''' Kicks a user from a chat. Kicking yourself (``'me'``) will result in leaving the chat. .. note:: Attempting to kick someone who was banned will remove their restrictions (and thus unbanning them), since kicking is just ban + unban. Arguments entity (`entity`): The channel or chat where the user should be kicked from. user (`entity`, optional): The user to kick. Returns Returns the service `Message <telethon.tl.custom.message.Message>` produced about a user being kicked, if any. Example .. code-block:: python # Kick some user from some chat, and deleting the service message msg = await client.kick_participant(chat, user) await msg.delete() # Leaving chat await client.kick_participant(chat, 'me') ''' pass async def get_permissions( self: 'TelegramClient', entity: 'hints.EntityLike', user: 'hints.EntityLike' = None ) -> 'typing.Optional[custom.ParticipantPermissions]': ''' Fetches the permissions of a user in a specific chat or channel or get Default Restricted Rights of Chat or Channel. .. note:: This request has to fetch the entire chat for small group chats, which can get somewhat expensive, so use of a cache is advised. Arguments entity (`entity`): The channel or chat the user is participant of. user (`entity`, optional): Target user. Returns A `ParticipantPermissions <telethon.tl.custom.participantpermissions.ParticipantPermissions>` instance. Refer to its documentation to see what properties are available. Example .. code-block:: python permissions = await client.get_permissions(chat, user) if permissions.is_admin: # do something # Get Banned Permissions of Chat await client.get_permissions(chat) ''' pass async def get_stats( self: 'TelegramClient', entity: 'hints.EntityLike', message: 'typing.Union[int, types.Message]' = None, ): ''' Retrieves statistics from the given megagroup or broadcast channel. Note that some restrictions apply before being able to fetch statistics, in particular the channel must have enough members (for megagroups, this requires `at least 500 members`_). Arguments entity (`entity`): The channel from which to get statistics. message (`int` | ``Message``, optional): The message ID from which to get statistics, if your goal is to obtain the statistics of a single message. Raises If the given entity is not a channel (broadcast or megagroup), a `TypeError` is raised. If there are not enough members (poorly named) errors such as ``telethon.errors.ChatAdminRequiredError`` will appear. Returns If both ``entity`` and ``message`` were provided, returns :tl:`MessageStats`. Otherwise, either :tl:`BroadcastStats` or :tl:`MegagroupStats`, depending on whether the input belonged to a broadcast channel or megagroup. Example .. code-block:: python # Some megagroup or channel username or ID to fetch channel = -100123 stats = await client.get_stats(channel) print('Stats from', stats.period.min_date, 'to', stats.period.max_date, ':') print(stats.stringify()) .. _`at least 500 members`: https://telegram.org/blog/profile-videos-people-nearby-and-more ''' pass
13
12
77
14
25
37
4
1.45
0
13
5
0
12
0
12
12
940
188
307
124
198
445
117
27
104
9
0
3
43
146,743
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/sessions/memory.py
telethon.sessions.memory.MemorySession
class MemorySession(Session): def __init__(self): super().__init__() self._dc_id = 0 self._server_address = None self._port = None self._auth_key = None self._takeout_id = None self._files = {} self._entities = set() self._update_states = {} def set_dc(self, dc_id, server_address, port): self._dc_id = dc_id or 0 self._server_address = server_address self._port = port @property def dc_id(self): return self._dc_id @property def server_address(self): return self._server_address @property def port(self): return self._port @property def auth_key(self): return self._auth_key @auth_key.setter def auth_key(self, value): self._auth_key = value @property def takeout_id(self): return self._takeout_id @takeout_id.setter def takeout_id(self, value): self._takeout_id = value def get_update_state(self, entity_id): return self._update_states.get(entity_id, None) def set_update_state(self, entity_id, state): self._update_states[entity_id] = state def get_update_states(self): return self._update_states.items() def close(self): pass def save(self): pass def delete(self): pass @staticmethod def _entity_values_to_row(id, hash, username, phone, name): # While this is a simple implementation it might be overrode by, # other classes so they don't need to implement the plural form # of the method. Don't remove. return id, hash, username, phone, name def _entity_to_row(self, e): if not isinstance(e, TLObject): return try: p = utils.get_input_peer(e, allow_self=False) marked_id = utils.get_peer_id(p) except TypeError: # Note: `get_input_peer` already checks for non-zero `access_hash`. # See issues #354 and #392. It also checks that the entity # is not `min`, because its `access_hash` cannot be used # anywhere (since layer 102, there are two access hashes). return if isinstance(p, (InputPeerUser, InputPeerChannel)): p_hash = p.access_hash elif isinstance(p, InputPeerChat): p_hash = 0 else: return username = getattr(e, 'username', None) or None if username is not None: username = username.lower() phone = getattr(e, 'phone', None) name = utils.get_display_name(e) or None return self._entity_values_to_row( marked_id, p_hash, username, phone, name ) def _entities_to_rows(self, tlo): if not isinstance(tlo, TLObject) and utils.is_list_like(tlo): # This may be a list of users already for instance entities = tlo else: entities = [] if hasattr(tlo, 'user'): entities.append(tlo.user) if hasattr(tlo, 'chat'): entities.append(tlo.chat) if hasattr(tlo, 'chats') and utils.is_list_like(tlo.chats): entities.extend(tlo.chats) if hasattr(tlo, 'users') and utils.is_list_like(tlo.users): entities.extend(tlo.users) rows = [] # Rows to add (id, hash, username, phone, name) for e in entities: row = self._entity_to_row(e) if row: rows.append(row) return rows def process_entities(self, tlo): self._entities |= set(self._entities_to_rows(tlo)) def get_entity_rows_by_phone(self, phone): try: return next((id, hash) for id, hash, _, found_phone, _ in self._entities if found_phone == phone) except StopIteration: pass def get_entity_rows_by_username(self, username): try: return next((id, hash) for id, hash, found_username, _, _ in self._entities if found_username == username) except StopIteration: pass def get_entity_rows_by_name(self, name): try: return next((id, hash) for id, hash, _, _, found_name in self._entities if found_name == name) except StopIteration: pass def get_entity_rows_by_id(self, id, exact=True): try: if exact: return next((found_id, hash) for found_id, hash, _, _, _ in self._entities if found_id == id) else: ids = ( utils.get_peer_id(PeerUser(id)), utils.get_peer_id(PeerChat(id)), utils.get_peer_id(PeerChannel(id)) ) return next((found_id, hash) for found_id, hash, _, _, _ in self._entities if found_id in ids) except StopIteration: pass def get_input_entity(self, key): try: if key.SUBCLASS_OF_ID in (0xc91c90b6, 0xe669bf46, 0x40f202fd): # hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel')) # We already have an Input version, so nothing else required return key # Try to early return if this key can be casted as input peer return utils.get_input_peer(key) except (AttributeError, TypeError): # Not a TLObject or can't be cast into InputPeer if isinstance(key, TLObject): key = utils.get_peer_id(key) exact = True else: exact = not isinstance(key, int) or key < 0 result = None if isinstance(key, str): phone = utils.parse_phone(key) if phone: result = self.get_entity_rows_by_phone(phone) else: username, invite = utils.parse_username(key) if username and not invite: result = self.get_entity_rows_by_username(username) else: tup = utils.resolve_invite_link(key)[1] if tup: result = self.get_entity_rows_by_id(tup, exact=False) elif isinstance(key, int): result = self.get_entity_rows_by_id(key, exact) if not result and isinstance(key, str): result = self.get_entity_rows_by_name(key) if result: entity_id, entity_hash = result # unpack resulting tuple entity_id, kind = utils.resolve_id(entity_id) # removes the mark and returns type of entity if kind == PeerUser: return InputPeerUser(entity_id, entity_hash) elif kind == PeerChat: return InputPeerChat(entity_id) elif kind == PeerChannel: return InputPeerChannel(entity_id, entity_hash) else: raise ValueError('Could not find input entity with key ', key) def cache_file(self, md5_digest, file_size, instance): if not isinstance(instance, (InputDocument, InputPhoto)): raise TypeError('Cannot cache %s instance' % type(instance)) key = (md5_digest, file_size, _SentFileType.from_type(type(instance))) value = (instance.id, instance.access_hash) self._files[key] = value def get_file(self, md5_digest, file_size, cls): key = (md5_digest, file_size, _SentFileType.from_type(cls)) try: return cls(*self._files[key]) except KeyError: return None
class MemorySession(Session): def __init__(self): pass def set_dc(self, dc_id, server_address, port): pass @property def dc_id(self): pass @property def server_address(self): pass @property def port(self): pass @property def auth_key(self): pass @auth_key.setter def auth_key(self): pass @property def takeout_id(self): pass @takeout_id.setter def takeout_id(self): pass def get_update_state(self, entity_id): pass def set_update_state(self, entity_id, state): pass def get_update_states(self): pass def close(self): pass def save(self): pass def delete(self): pass @staticmethod def _entity_values_to_row(id, hash, username, phone, name): pass def _entity_to_row(self, e): pass def _entities_to_rows(self, tlo): pass def process_entities(self, tlo): pass def get_entity_rows_by_phone(self, phone): pass def get_entity_rows_by_username(self, username): pass def get_entity_rows_by_name(self, name): pass def get_entity_rows_by_id(self, id, exact=True): pass def get_input_entity(self, key): pass def cache_file(self, md5_digest, file_size, instance): pass def get_file(self, md5_digest, file_size, cls): pass
35
0
7
0
7
1
2
0.08
1
10
1
2
25
8
26
67
225
34
178
68
143
15
148
56
121
14
5
4
58
146,744
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/buttons.py
telethon.client.buttons.ButtonMethods
class ButtonMethods: @staticmethod def build_reply_markup( buttons: 'typing.Optional[hints.MarkupLike]', inline_only: bool = False) -> 'typing.Optional[types.TypeReplyMarkup]': """ Builds a :tl:`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons. Does nothing if either no buttons are provided or the provided argument is already a reply markup. You should consider using this method if you are going to reuse the markup very often. Otherwise, it is not necessary. This method is **not** asynchronous (don't use ``await`` on it). Arguments buttons (`hints.MarkupLike`): The button, list of buttons, array of buttons or markup to convert into a markup. inline_only (`bool`, optional): Whether the buttons **must** be inline buttons only or not. Example .. code-block:: python from telethon import Button markup = client.build_reply_markup(Button.inline('hi')) # later await client.send_message(chat, 'click me', buttons=markup) """ if buttons is None: return None try: if buttons.SUBCLASS_OF_ID == 0xe2e10ef2: return buttons # crc32(b'ReplyMarkup'): except AttributeError: pass if not utils.is_list_like(buttons): buttons = [[buttons]] elif not buttons or not utils.is_list_like(buttons[0]): buttons = [buttons] is_inline = False is_normal = False resize = None single_use = None selective = None rows = [] for row in buttons: current = [] for button in row: if isinstance(button, custom.Button): if button.resize is not None: resize = button.resize if button.single_use is not None: single_use = button.single_use if button.selective is not None: selective = button.selective button = button.button elif isinstance(button, custom.MessageButton): button = button.button inline = custom.Button._is_inline(button) is_inline |= inline is_normal |= not inline if button.SUBCLASS_OF_ID == 0xbad74a3: # 0xbad74a3 == crc32(b'KeyboardButton') current.append(button) if current: rows.append(types.KeyboardButtonRow(current)) if inline_only and is_normal: raise ValueError('You cannot use non-inline buttons here') elif is_inline == is_normal and is_normal: raise ValueError('You cannot mix inline with normal buttons') elif is_inline: return types.ReplyInlineMarkup(rows) # elif is_normal: return types.ReplyKeyboardMarkup( rows, resize=resize, single_use=single_use, selective=selective)
class ButtonMethods: @staticmethod def build_reply_markup( buttons: 'typing.Optional[hints.MarkupLike]', inline_only: bool = False) -> 'typing.Optional[types.TypeReplyMarkup]': ''' Builds a :tl:`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons. Does nothing if either no buttons are provided or the provided argument is already a reply markup. You should consider using this method if you are going to reuse the markup very often. Otherwise, it is not necessary. This method is **not** asynchronous (don't use ``await`` on it). Arguments buttons (`hints.MarkupLike`): The button, list of buttons, array of buttons or markup to convert into a markup. inline_only (`bool`, optional): Whether the buttons **must** be inline buttons only or not. Example .. code-block:: python from telethon import Button markup = client.build_reply_markup(Button.inline('hi')) # later await client.send_message(chat, 'click me', buttons=markup) ''' pass
3
1
88
17
48
24
18
0.48
0
3
0
0
0
0
1
1
90
17
50
15
45
24
42
12
40
18
0
4
18
146,745
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/bots.py
telethon.client.bots.BotMethods
class BotMethods: async def inline_query( self: 'TelegramClient', bot: 'hints.EntityLike', query: str, *, entity: 'hints.EntityLike' = None, offset: str = None, geo_point: 'types.GeoPoint' = None) -> custom.InlineResults: """ Makes an inline query to the specified bot (``@vote New Poll``). Arguments bot (`entity`): The bot entity to which the inline query should be made. query (`str`): The query that should be made to the bot. entity (`entity`, optional): The entity where the inline query is being made from. Certain bots use this to display different results depending on where it's used, such as private chats, groups or channels. If specified, it will also be the default entity where the message will be sent after clicked. Otherwise, the "empty peer" will be used, which some bots may not handle correctly. offset (`str`, optional): The string offset to use for the bot. geo_point (:tl:`GeoPoint`, optional) The geo point location information to send to the bot for localised results. Available under some bots. Returns A list of `custom.InlineResult <telethon.tl.custom.inlineresult.InlineResult>`. Example .. code-block:: python # Make an inline query to @like results = await client.inline_query('like', 'Do you like Telethon?') # Send the first result to some chat message = await results[0].click('TelethonOffTopic') """ bot = await self.get_input_entity(bot) if entity: peer = await self.get_input_entity(entity) else: peer = types.InputPeerEmpty() result = await self(functions.messages.GetInlineBotResultsRequest( bot=bot, peer=peer, query=query, offset=offset or '', geo_point=geo_point )) return custom.InlineResults(self, result, entity=peer if entity else None)
class BotMethods: async def inline_query( self: 'TelegramClient', bot: 'hints.EntityLike', query: str, *, entity: 'hints.EntityLike' = None, offset: str = None, geo_point: 'types.GeoPoint' = None) -> custom.InlineResults: ''' Makes an inline query to the specified bot (``@vote New Poll``). Arguments bot (`entity`): The bot entity to which the inline query should be made. query (`str`): The query that should be made to the bot. entity (`entity`, optional): The entity where the inline query is being made from. Certain bots use this to display different results depending on where it's used, such as private chats, groups or channels. If specified, it will also be the default entity where the message will be sent after clicked. Otherwise, the "empty peer" will be used, which some bots may not handle correctly. offset (`str`, optional): The string offset to use for the bot. geo_point (:tl:`GeoPoint`, optional) The geo point location information to send to the bot for localised results. Available under some bots. Returns A list of `custom.InlineResult <telethon.tl.custom.inlineresult.InlineResult>`. Example .. code-block:: python # Make an inline query to @like results = await client.inline_query('like', 'Do you like Telethon?') # Send the first result to some chat message = await results[0].click('TelethonOffTopic') ''' pass
2
1
62
12
21
29
3
1.32
0
1
0
0
1
0
1
1
63
12
22
11
13
29
8
4
6
3
0
1
3
146,746
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/account.py
telethon.client.account._TakeoutClient
class _TakeoutClient: """ Proxy object over the client. """ __PROXY_INTERFACE = ('__enter__', '__exit__', '__aenter__', '__aexit__') def __init__(self, finalize, client, request): # We use the name mangling for attributes to make them inaccessible # from within the shadowed client object and to distinguish them from # its own attributes where needed. self.__finalize = finalize self.__client = client self.__request = request self.__success = None @property def success(self): return self.__success @success.setter def success(self, value): self.__success = value async def __aenter__(self): # Enter/Exit behaviour is "overrode", we don't want to call start. client = self.__client if client.session.takeout_id is None: client.session.takeout_id = (await client(self.__request)).id elif self.__request is not None: raise ValueError("Can't send a takeout request while another " "takeout for the current session still not been finished yet.") return self async def __aexit__(self, exc_type, exc_value, traceback): if self.__success is None and self.__finalize: self.__success = exc_type is None if self.__success is not None: result = await self(functions.account.FinishTakeoutSessionRequest( self.__success)) if not result: raise ValueError("Failed to finish the takeout.") self.session.takeout_id = None __enter__ = helpers._sync_enter __exit__ = helpers._sync_exit async def __call__(self, request, ordered=False): takeout_id = self.__client.session.takeout_id if takeout_id is None: raise ValueError('Takeout mode has not been initialized ' '(are you calling outside of "with"?)') single = not utils.is_list_like(request) requests = ((request,) if single else request) wrapped = [] for r in requests: if not isinstance(r, TLRequest): raise _NOT_A_REQUEST() await r.resolve(self, utils) wrapped.append(functions.InvokeWithTakeoutRequest(takeout_id, r)) return await self.__client( wrapped[0] if single else wrapped, ordered=ordered) def __getattribute__(self, name): # We access class via type() because __class__ will recurse infinitely. # Also note that since we've name-mangled our own class attributes, # they'll be passed to __getattribute__() as already decorated. For # example, 'self.__client' will be passed as '_TakeoutClient__client'. # https://docs.python.org/3/tutorial/classes.html#private-variables if name.startswith('__') and name not in type(self).__PROXY_INTERFACE: raise AttributeError # force call of __getattr__ # Try to access attribute in the proxy object and check for the same # attribute in the shadowed object (through our __getattr__) if failed. return super().__getattribute__(name) def __getattr__(self, name): value = getattr(self.__client, name) if inspect.ismethod(value): # Emulate bound methods behavior by partially applying our proxy # class as the self parameter instead of the client. return functools.partial( getattr(self.__client.__class__, name), self) return value def __setattr__(self, name, value): if name.startswith('_{}__'.format(type(self).__name__.lstrip('_'))): # This is our own name-mangled attribute, keep calm. return super().__setattr__(name, value) return setattr(self.__client, name, value)
class _TakeoutClient: ''' Proxy object over the client. ''' def __init__(self, finalize, client, request): pass @property def success(self): pass @success.setter def success(self): pass async def __aenter__(self): pass async def __aexit__(self, exc_type, exc_value, traceback): pass async def __call__(self, request, ordered=False): pass def __getattribute__(self, name): pass def __getattr__(self, name): pass def __setattr__(self, name, value): pass
12
1
8
1
6
2
2
0.3
0
6
1
0
9
4
9
9
93
15
61
27
49
18
53
25
43
6
0
2
22
146,747
LonamiWebs/Telethon
LonamiWebs_Telethon/telethon/client/account.py
telethon.client.account.AccountMethods
class AccountMethods: def takeout( self: 'TelegramClient', finalize: bool = True, *, contacts: bool = None, users: bool = None, chats: bool = None, megagroups: bool = None, channels: bool = None, files: bool = None, max_file_size: bool = None) -> 'TelegramClient': """ Returns a :ref:`telethon-client` which calls methods behind a takeout session. It does so by creating a proxy object over the current client through which making requests will use :tl:`InvokeWithTakeoutRequest` to wrap them. In other words, returns the current client modified so that requests are done as a takeout: Some of the calls made through the takeout session will have lower flood limits. This is useful if you want to export the data from conversations or mass-download media, since the rate limits will be lower. Only some requests will be affected, and you will need to adjust the `wait_time` of methods like `client.iter_messages <telethon.client.messages.MessageMethods.iter_messages>`. By default, all parameters are `None`, and you need to enable those you plan to use by setting them to either `True` or `False`. You should ``except errors.TakeoutInitDelayError as e``, since this exception will raise depending on the condition of the session. You can then access ``e.seconds`` to know how long you should wait for before calling the method again. There's also a `success` property available in the takeout proxy object, so from the `with` body you can set the boolean result that will be sent back to Telegram. But if it's left `None` as by default, then the action is based on the `finalize` parameter. If it's `True` then the takeout will be finished, and if no exception occurred during it, then `True` will be considered as a result. Otherwise, the takeout will not be finished and its ID will be preserved for future usage as `client.session.takeout_id <telethon.sessions.abstract.Session.takeout_id>`. Arguments finalize (`bool`): Whether the takeout session should be finalized upon exit or not. contacts (`bool`): Set to `True` if you plan on downloading contacts. users (`bool`): Set to `True` if you plan on downloading information from users and their private conversations with you. chats (`bool`): Set to `True` if you plan on downloading information from small group chats, such as messages and media. megagroups (`bool`): Set to `True` if you plan on downloading information from megagroups (channels), such as messages and media. channels (`bool`): Set to `True` if you plan on downloading information from broadcast channels, such as messages and media. files (`bool`): Set to `True` if you plan on downloading media and you don't only wish to export messages. max_file_size (`int`): The maximum file size, in bytes, that you plan to download for each message with media. Example .. code-block:: python from telethon import errors try: async with client.takeout() as takeout: await client.get_messages('me') # normal call await takeout.get_messages('me') # wrapped through takeout (less limits) async for message in takeout.iter_messages(chat, wait_time=0): ... # Do something with the message except errors.TakeoutInitDelayError as e: print('Must wait', e.seconds, 'before takeout') """ request_kwargs = dict( contacts=contacts, message_users=users, message_chats=chats, message_megagroups=megagroups, message_channels=channels, files=files, file_max_size=max_file_size ) arg_specified = (arg is not None for arg in request_kwargs.values()) if self.session.takeout_id is None or any(arg_specified): request = functions.account.InitTakeoutSessionRequest( **request_kwargs) else: request = None return _TakeoutClient(finalize, self, request) async def end_takeout(self: 'TelegramClient', success: bool) -> bool: """ Finishes the current takeout session. Arguments success (`bool`): Whether the takeout completed successfully or not. Returns `True` if the operation was successful, `False` otherwise. Example .. code-block:: python await client.end_takeout(success=False) """ try: async with _TakeoutClient(True, self, None) as takeout: takeout.success = success except ValueError: return False return True
class AccountMethods: def takeout( self: 'TelegramClient', finalize: bool = True, *, contacts: bool = None, users: bool = None, chats: bool = None, megagroups: bool = None, channels: bool = None, files: bool = None, max_file_size: bool = None) -> 'TelegramClient': ''' Returns a :ref:`telethon-client` which calls methods behind a takeout session. It does so by creating a proxy object over the current client through which making requests will use :tl:`InvokeWithTakeoutRequest` to wrap them. In other words, returns the current client modified so that requests are done as a takeout: Some of the calls made through the takeout session will have lower flood limits. This is useful if you want to export the data from conversations or mass-download media, since the rate limits will be lower. Only some requests will be affected, and you will need to adjust the `wait_time` of methods like `client.iter_messages <telethon.client.messages.MessageMethods.iter_messages>`. By default, all parameters are `None`, and you need to enable those you plan to use by setting them to either `True` or `False`. You should ``except errors.TakeoutInitDelayError as e``, since this exception will raise depending on the condition of the session. You can then access ``e.seconds`` to know how long you should wait for before calling the method again. There's also a `success` property available in the takeout proxy object, so from the `with` body you can set the boolean result that will be sent back to Telegram. But if it's left `None` as by default, then the action is based on the `finalize` parameter. If it's `True` then the takeout will be finished, and if no exception occurred during it, then `True` will be considered as a result. Otherwise, the takeout will not be finished and its ID will be preserved for future usage as `client.session.takeout_id <telethon.sessions.abstract.Session.takeout_id>`. Arguments finalize (`bool`): Whether the takeout session should be finalized upon exit or not. contacts (`bool`): Set to `True` if you plan on downloading contacts. users (`bool`): Set to `True` if you plan on downloading information from users and their private conversations with you. chats (`bool`): Set to `True` if you plan on downloading information from small group chats, such as messages and media. megagroups (`bool`): Set to `True` if you plan on downloading information from megagroups (channels), such as messages and media. channels (`bool`): Set to `True` if you plan on downloading information from broadcast channels, such as messages and media. files (`bool`): Set to `True` if you plan on downloading media and you don't only wish to export messages. max_file_size (`int`): The maximum file size, in bytes, that you plan to download for each message with media. Example .. code-block:: python from telethon import errors try: async with client.takeout() as takeout: await client.get_messages('me') # normal call await takeout.get_messages('me') # wrapped through takeout (less limits) async for message in takeout.iter_messages(chat, wait_time=0): ... # Do something with the message except errors.TakeoutInitDelayError as e: print('Must wait', e.seconds, 'before takeout') ''' pass async def end_takeout(self: 'TelegramClient', success: bool) -> bool: ''' Finishes the current takeout session. Arguments success (`bool`): Whether the takeout completed successfully or not. Returns `True` if the operation was successful, `False` otherwise. Example .. code-block:: python await client.end_takeout(success=False) ''' pass
3
2
66
12
17
37
2
2.11
0
4
1
0
2
0
2
2
134
25
35
17
22
74
15
6
12
2
0
2
4