/usr/lib/python3/dist-packages/twitter/api.py is in python3-twitter 3.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 | #!/usr/bin/env python
#
#
# Copyright 2007-2016 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library that provides a Python interface to the Twitter API"""
from __future__ import division
from __future__ import print_function
import json
import sys
import gzip
import time
import base64
import re
import requests
from requests_oauthlib import OAuth1, OAuth2
import io
import warnings
from uuid import uuid4
import os
try:
# python 3
from urllib.parse import urlparse, urlunparse, urlencode
from urllib.request import urlopen
from urllib.request import __version__ as urllib_version
except ImportError:
from urlparse import urlparse, urlunparse
from urllib2 import urlopen
from urllib import urlencode
from urllib import __version__ as urllib_version
from twitter import (
__version__,
_FileCache,
Category,
DirectMessage,
List,
Status,
Trend,
User,
UserStatus,
)
from twitter.ratelimit import RateLimit
from twitter.twitter_utils import (
calc_expected_status_length,
is_url,
parse_media_file,
enf_type)
from twitter.error import (
TwitterError,
PythonTwitterDeprecationWarning330,
)
if sys.version_info > (3,):
long = int
CHARACTER_LIMIT = 140
# A singleton representing a lazily instantiated FileCache.
DEFAULT_CACHE = object()
class Api(object):
"""A python interface into the Twitter API
By default, the Api caches results for 1 minute.
Example usage:
To create an instance of the twitter.Api class, with no authentication:
>>> import twitter
>>> api = twitter.Api()
To fetch a single user's public status messages, where "user" is either
a Twitter "short name" or their user id.
>>> statuses = api.GetUserTimeline(user)
>>> print([s.text for s in statuses])
To use authentication, instantiate the twitter.Api class with a
consumer key and secret; and the oAuth key and secret:
>>> api = twitter.Api(consumer_key='twitter consumer key',
consumer_secret='twitter consumer secret',
access_token_key='the_key_given',
access_token_secret='the_key_secret')
To fetch your friends (after being authenticated):
>>> users = api.GetFriends()
>>> print([u.name for u in users])
To post a twitter status message (after being authenticated):
>>> status = api.PostUpdate('I love python-twitter!')
>>> print(status.text)
I love python-twitter!
There are many other methods, including:
>>> api.PostUpdates(status)
>>> api.PostDirectMessage(user, text)
>>> api.GetUser(user)
>>> api.GetReplies()
>>> api.GetUserTimeline(user)
>>> api.GetHomeTimeline()
>>> api.GetStatus(status_id)
>>> api.DestroyStatus(status_id)
>>> api.GetFriends(user)
>>> api.GetFollowers()
>>> api.GetFeatured()
>>> api.GetDirectMessages()
>>> api.GetSentDirectMessages()
>>> api.PostDirectMessage(user, text)
>>> api.DestroyDirectMessage(message_id)
>>> api.DestroyFriendship(user)
>>> api.CreateFriendship(user)
>>> api.LookupFriendship(user)
>>> api.VerifyCredentials()
"""
DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
_API_REALM = 'Twitter API'
def __init__(self,
consumer_key=None,
consumer_secret=None,
access_token_key=None,
access_token_secret=None,
application_only_auth=False,
input_encoding=None,
request_headers=None,
cache=DEFAULT_CACHE,
base_url=None,
stream_url=None,
upload_url=None,
chunk_size=1024 * 1024,
use_gzip_compression=False,
debugHTTP=False,
timeout=None,
sleep_on_rate_limit=False,
tweet_mode='compat',
proxies=None):
"""Instantiate a new twitter.Api object.
Args:
consumer_key (str):
Your Twitter user's consumer_key.
consumer_secret (str):
Your Twitter user's consumer_secret.
access_token_key (str):
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret (str):
The oAuth access token's secret, also retrieved
from the get_access_token.py run.
application_only_auth:
Use Application-Only Auth instead of User Auth.
Defaults to False [Optional]
input_encoding (str, optional):
The encoding used to encode input strings.
request_header (dict, optional):
A dictionary of additional HTTP request headers.
cache (object, optional):
The cache instance to use. Defaults to DEFAULT_CACHE.
Use None to disable caching.
base_url (str, optional):
The base URL to use to contact the Twitter API.
Defaults to https://api.twitter.com.
stream_url (str, optional):
The base URL to use for streaming endpoints.
Defaults to 'https://stream.twitter.com/1.1'.
upload_url (str, optional):
The base URL to use for uploads. Defaults to 'https://upload.twitter.com/1.1'.
chunk_size (int, optional):
Chunk size to use for chunked (multi-part) uploads of images/videos/gifs.
Defaults to 1MB. Anything under 16KB and you run the risk of erroring out
on 15MB files.
use_gzip_compression (bool, optional):
Set to True to tell enable gzip compression for any call
made to Twitter. Defaults to False.
debugHTTP (bool, optional):
Set to True to enable debug output from urllib2 when performing
any HTTP requests. Defaults to False.
timeout (int, optional):
Set timeout (in seconds) of the http/https requests. If None the
requests lib default will be used. Defaults to None.
sleep_on_rate_limit (bool, optional):
Whether to sleep an appropriate amount of time if a rate limit is hit for
an endpoint.
tweet_mode (str, optional):
Whether to use the new (as of Sept. 2016) extended tweet mode. See docs for
details. Choices are ['compatibility', 'extended'].
proxies (dict, optional):
A dictionary of proxies for the request to pass through, if not specified
allows requests lib to use environmental variables for proxy if any.
"""
# check to see if the library is running on a Google App Engine instance
# see GAE.rst for more information
if os.environ:
if 'APPENGINE_RUNTIME' in os.environ.keys():
import requests_toolbelt.adapters.appengine # Adapter ensures requests use app engine's urlfetch
requests_toolbelt.adapters.appengine.monkeypatch()
cache = None # App Engine does not like this caching strategy, disable caching
self.SetCache(cache)
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._input_encoding = input_encoding
self._use_gzip = use_gzip_compression
self._debugHTTP = debugHTTP
self._shortlink_size = 19
self._timeout = timeout
self.__auth = None
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._InitializeDefaultParameters()
self.rate_limit = RateLimit()
self.sleep_on_rate_limit = sleep_on_rate_limit
self.tweet_mode = tweet_mode
self.proxies = proxies
if base_url is None:
self.base_url = 'https://api.twitter.com/1.1'
else:
self.base_url = base_url
if stream_url is None:
self.stream_url = 'https://stream.twitter.com/1.1'
else:
self.stream_url = stream_url
if upload_url is None:
self.upload_url = 'https://upload.twitter.com/1.1'
else:
self.upload_url = upload_url
self.chunk_size = chunk_size
if self.chunk_size < 1024 * 16:
warnings.warn((
"A chunk size lower than 16384 may result in too many "
"requests to the Twitter API when uploading videos. You are "
"strongly advised to increase it above 16384"
))
if (consumer_key and not
(application_only_auth or all([access_token_key, access_token_secret]))):
raise TwitterError({'message': "Missing oAuth Consumer Key or Access Token"})
self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret,
application_only_auth)
if debugHTTP:
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
def GetAppOnlyAuthToken(self, consumer_key, consumer_secret):
"""
Generate a Bearer Token from consumer_key and consumer_secret
"""
from urllib import quote_plus
import base64
key = quote_plus(consumer_key)
secret = quote_plus(consumer_secret)
bearer_token = base64.b64encode('{}:{}'.format(key, secret))
post_headers = {
'Authorization': 'Basic ' + bearer_token,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
res = requests.post(url='https://api.twitter.com/oauth2/token',
data={'grant_type': 'client_credentials'},
headers=post_headers)
bearer_creds = res.json()
return bearer_creds
def SetCredentials(self,
consumer_key,
consumer_secret,
access_token_key=None,
access_token_secret=None,
application_only_auth=False):
"""Set the consumer_key and consumer_secret for this instance
Args:
consumer_key:
The consumer_key of the twitter account.
consumer_secret:
The consumer_secret for the twitter account.
access_token_key:
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret:
The oAuth access token's secret, also retrieved
from the get_access_token.py run.
application_only_auth:
Whether to generate a bearer token and use Application-Only Auth
"""
self._consumer_key = consumer_key
self._consumer_secret = consumer_secret
self._access_token_key = access_token_key
self._access_token_secret = access_token_secret
if application_only_auth:
self._bearer_token = self.GetAppOnlyAuthToken(consumer_key, consumer_secret)
self.__auth = OAuth2(token=self._bearer_token)
else:
auth_list = [consumer_key, consumer_secret,
access_token_key, access_token_secret]
if all(auth_list):
self.__auth = OAuth1(consumer_key, consumer_secret,
access_token_key, access_token_secret)
self._config = None
def GetHelpConfiguration(self):
"""Get basic help configuration details from Twitter.
Args:
None
Returns:
dict: Sets self._config and returns dict of help config values.
"""
if self._config is None:
url = '%s/help/configuration.json' % self.base_url
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
self._config = data
return self._config
def GetShortUrlLength(self, https=False):
"""Returns number of characters reserved per URL included in a tweet.
Args:
https (bool, optional):
If True, return number of characters reserved for https urls
or, if False, return number of character reserved for http urls.
Returns:
(int): Number of characters reserved per URL.
"""
config = self.GetHelpConfiguration()
if https:
return config['short_url_length_https']
else:
return config['short_url_length']
def ClearCredentials(self):
"""Clear any credentials for this instance
"""
self._consumer_key = None
self._consumer_secret = None
self._access_token_key = None
self._access_token_secret = None
self._bearer_token = None
self.__auth = None # for request upgrade
def GetSearch(self,
term=None,
raw_query=None,
geocode=None,
since_id=None,
max_id=None,
until=None,
since=None,
count=15,
lang=None,
locale=None,
result_type="mixed",
include_entities=None):
"""Return twitter search results for a given term. You must specify one
of term, geocode, or raw_query.
Args:
term (str, optional):
Term to search by. Optional if you include geocode.
raw_query (str, optional):
A raw query as a string. This should be everything after the "?" in
the URL (i.e., the query parameters). You are responsible for all
type checking and ensuring that the query string is properly
formatted, as it will only be URL-encoded before be passed directly
to Twitter with no other checks performed. For advanced usage only.
*This will override any other parameters passed*
since_id (int, optional):
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available.
max_id (int, optional):
Returns only statuses with an ID less than (that is, older
than) or equal to the specified ID.
until (str, optional):
Returns tweets generated before the given date. Date should be
formatted as YYYY-MM-DD.
since (str, optional):
Returns tweets generated since the given date. Date should be
formatted as YYYY-MM-DD.
geocode (str or list or tuple, optional):
Geolocation within which to search for tweets. Can be either a
string in the form of "latitude,longitude,radius" where latitude
and longitude are floats and radius is a string such as "1mi" or
"1km" ("mi" or "km" are the only units allowed). For example:
>>> api.GetSearch(geocode="37.781157,-122.398720,1mi").
Otherwise, you can pass a list of either floats or strings for
lat/long and a string for radius:
>>> api.GetSearch(geocode=[37.781157, -122.398720, "1mi"])
>>> # or:
>>> api.GetSearch(geocode=(37.781157, -122.398720, "1mi"))
>>> # or:
>>> api.GetSearch(geocode=("37.781157", "-122.398720", "1mi"))
count (int, optional):
Number of results to return. Default is 15 and maxmimum that
Twitter returns is 100 irrespective of what you type in.
lang (str, optional):
Language for results as ISO 639-1 code. Default is None
(all languages).
locale (str, optional):
Language of the search query. Currently only 'ja' is effective.
This is intended for language-specific consumers and the default
should work in the majority of cases.
result_type (str, optional):
Type of result which should be returned. Default is "mixed".
Valid options are "mixed, "recent", and "popular".
include_entities (bool, optional):
If True, each tweet will include a node called "entities".
This node offers a variety of metadata about the tweet in a
discrete structure, including: user_mentions, urls, and
hashtags.
Returns:
list: A sequence of twitter.Status instances, one for each message
containing the term, within the bounds of the geocoded area, or
given by the raw_query.
"""
url = '%s/search/tweets.json' % self.base_url
parameters = {}
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if until:
parameters['until'] = enf_type('until', str, until)
if since:
parameters['since'] = enf_type('since', str, since)
if lang:
parameters['lang'] = enf_type('lang', str, lang)
if locale:
parameters['locale'] = enf_type('locale', str, locale)
if term is None and geocode is None and raw_query is None:
return []
if term is not None:
parameters['q'] = term
if geocode is not None:
if isinstance(geocode, list) or isinstance(geocode, tuple):
parameters['geocode'] = ','.join([str(geo) for geo in geocode])
else:
parameters['geocode'] = enf_type('geocode', str, geocode)
if include_entities:
parameters['include_entities'] = enf_type('include_entities',
bool,
include_entities)
parameters['count'] = enf_type('count', int, count)
if result_type in ["mixed", "popular", "recent"]:
parameters['result_type'] = result_type
if raw_query is not None:
url = "{url}?{raw_query}".format(
url=url,
raw_query=raw_query)
resp = self._RequestUrl(url, 'GET')
else:
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data.get('statuses', '')]
def GetUsersSearch(self,
term=None,
page=1,
count=20,
include_entities=None):
"""Return twitter user search results for a given term.
Args:
term:
Term to search by.
page:
Page of results to return. Default is 1
[Optional]
count:
Number of results to return. Default is 20
[Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata about the tweet in a
discrete structure, including: user_mentions, urls, and hashtags.
[Optional]
Returns:
A sequence of twitter.User instances, one for each message containing
the term
"""
# Build request parameters
parameters = {}
if term is not None:
parameters['q'] = term
if page != 1:
parameters['page'] = page
if include_entities:
parameters['include_entities'] = 1
try:
parameters['count'] = int(count)
except ValueError:
raise TwitterError({'message': "count must be an integer"})
# Make and send requests
url = '%s/users/search.json' % self.base_url
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [User.NewFromJsonDict(x) for x in data]
def GetTrendsCurrent(self, exclude=None):
"""Get the current top trending topics (global)
Args:
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each entry contains a trend.
"""
return self.GetTrendsWoeid(woeid=1, exclude=exclude)
def GetTrendsWoeid(self, woeid, exclude=None):
"""Return the top 10 trending topics for a specific WOEID, if trending
information is available for it.
Args:
woeid:
the Yahoo! Where On Earth ID for a location.
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each entry contains a trend.
"""
url = '%s/trends/place.json' % (self.base_url)
parameters = {'id': woeid}
if exclude:
parameters['exclude'] = exclude
resp = self._RequestUrl(url, verb='GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
trends = []
timestamp = data[0]['as_of']
for trend in data[0]['trends']:
trends.append(Trend.NewFromJsonDict(trend, timestamp=timestamp))
return trends
def GetUserSuggestionCategories(self):
""" Return the list of suggested user categories, this can be used in
GetUserSuggestion function
Returns:
A list of categories
"""
url = '%s/users/suggestions.json' % (self.base_url)
resp = self._RequestUrl(url, verb='GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
categories = []
for category in data:
categories.append(Category.NewFromJsonDict(category))
return categories
def GetUserSuggestion(self, category):
""" Returns a list of users in a category
Args:
category:
The Category object to limit the search by
Returns:
A list of users in that category
"""
url = '%s/users/suggestions/%s.json' % (self.base_url, category.slug)
resp = self._RequestUrl(url, verb='GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
users = []
for user in data['users']:
users.append(User.NewFromJsonDict(user))
return users
def GetHomeTimeline(self,
count=None,
since_id=None,
max_id=None,
trim_user=False,
exclude_replies=False,
contributor_details=False,
include_entities=True):
"""Fetch a collection of the most recent Tweets and retweets posted
by the authenticating user and the users they follow.
The home timeline is central to how most users interact with Twitter.
Args:
count:
Specifies the number of statuses to retrieve. May not be
greater than 200. Defaults to 20. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
trim_user:
When True, each tweet returned in a timeline will include a user
object including only the status authors numerical ID. Omit this
parameter to receive the complete user object. [Optional]
exclude_replies:
This parameter will prevent replies from appearing in the
returned timeline. Using exclude_replies with the count
parameter will mean you will receive up-to count tweets -
this is because the count parameter retrieves that many
tweets before filtering out retweets and replies. [Optional]
contributor_details:
This parameter enhances the contributors element of the
status response to include the screen_name of the contributor.
By default only the user_id of the contributor is included. [Optional]
include_entities:
The entities node will be disincluded when set to false.
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message
"""
url = '%s/statuses/home_timeline.json' % self.base_url
parameters = {}
if count is not None:
try:
if int(count) > 200:
raise TwitterError({'message': "'count' may not be greater than 200"})
except ValueError:
raise TwitterError({'message': "'count' must be an integer"})
parameters['count'] = count
if since_id:
try:
parameters['since_id'] = int(since_id)
except ValueError:
raise TwitterError({'message': "'since_id' must be an integer"})
if max_id:
try:
parameters['max_id'] = int(max_id)
except ValueError:
raise TwitterError({'message': "'max_id' must be an integer"})
if trim_user:
parameters['trim_user'] = 1
if exclude_replies:
parameters['exclude_replies'] = 1
if contributor_details:
parameters['contributor_details'] = 1
if not include_entities:
parameters['include_entities'] = 'false'
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data]
def GetUserTimeline(self,
user_id=None,
screen_name=None,
since_id=None,
max_id=None,
count=None,
include_rts=True,
trim_user=False,
exclude_replies=False):
"""Fetch the sequence of public Status messages for a single user.
The twitter.Api instance must be authenticated if the user is private.
Args:
user_id (int, optional):
Specifies the ID of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
screen_name (str, optional):
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID.
since_id (int, optional):
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available.
max_id (int, optional):
Returns only statuses with an ID less than (that is, older
than) or equal to the specified ID.
count (int, optional):
Specifies the number of statuses to retrieve. May not be
greater than 200.
include_rts (bool, optional):
If True, the timeline will contain native retweets (if they
exist) in addition to the standard stream of tweets.
trim_user (bool, optional):
If True, statuses will only contain the numerical user ID only.
Otherwise a full user object will be returned for each status.
exclude_replies (bool, optional)
If True, this will prevent replies from appearing in the returned
timeline. Using exclude_replies with the count parameter will mean you
will receive up-to count tweets - this is because the count parameter
retrieves that many tweets before filtering out retweets and replies.
This parameter is only supported for JSON and XML responses.
Returns:
A sequence of Status instances, one for each message up to count
"""
url = '%s/statuses/user_timeline.json' % (self.base_url)
parameters = {}
if user_id:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
parameters['screen_name'] = screen_name
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if count:
parameters['count'] = enf_type('count', int, count)
parameters['include_rts'] = enf_type('include_rts', bool, include_rts)
parameters['trim_user'] = enf_type('trim_user', bool, trim_user)
parameters['exclude_replies'] = enf_type('exclude_replies', bool, exclude_replies)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data]
def GetStatus(self,
status_id,
trim_user=False,
include_my_retweet=True,
include_entities=True,
include_ext_alt_text=True):
"""Returns a single status message, specified by the status_id parameter.
Args:
status_id:
The numeric ID of the status you are trying to retrieve.
trim_user:
When set to True, each tweet returned in a timeline will include
a user object including only the status authors numerical ID.
Omit this parameter to receive the complete user object. [Optional]
include_my_retweet:
When set to True, any Tweets returned that have been retweeted by
the authenticating user will include an additional
current_user_retweet node, containing the ID of the source status
for the retweet. [Optional]
include_entities:
If False, the entities node will be disincluded.
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
Returns:
A twitter.Status instance representing that status message
"""
url = '%s/statuses/show.json' % (self.base_url)
parameters = {
'id': enf_type('status_id', int, status_id),
'trim_user': enf_type('trim_user', bool, trim_user),
'include_my_retweet': enf_type('include_my_retweet', bool, include_my_retweet),
'include_entities': enf_type('include_entities', bool, include_entities),
'include_ext_alt_text': enf_type('include_ext_alt_text', bool, include_ext_alt_text)
}
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def GetStatusOembed(self,
status_id=None,
url=None,
maxwidth=None,
hide_media=False,
hide_thread=False,
omit_script=False,
align=None,
related=None,
lang=None):
"""Returns information allowing the creation of an embedded representation of a
Tweet on third party sites.
Specify tweet by the id or url parameter.
Args:
status_id:
The numeric ID of the status you are trying to embed.
url:
The url of the status you are trying to embed.
maxwidth:
The maximum width in pixels that the embed should be rendered at.
This value is constrained to be between 250 and 550 pixels. [Optional]
hide_media:
Specifies whether the embedded Tweet should automatically expand images. [Optional]
hide_thread:
Specifies whether the embedded Tweet should automatically show the original
message in the case that the embedded Tweet is a reply. [Optional]
omit_script:
Specifies whether the embedded Tweet HTML should include a <script>
element pointing to widgets.js. [Optional]
align:
Specifies whether the embedded Tweet should be left aligned, right aligned,
or centered in the page. [Optional]
related:
A comma sperated string of related screen names. [Optional]
lang:
Language code for the rendered embed. [Optional]
Returns:
A dictionary with the response.
"""
request_url = '%s/statuses/oembed.json' % (self.base_url)
parameters = {}
if status_id is not None:
try:
parameters['id'] = int(status_id)
except ValueError:
raise TwitterError({'message': "'status_id' must be an integer."})
elif url is not None:
parameters['url'] = url
else:
raise TwitterError({'message': "Must specify either 'status_id' or 'url'"})
if maxwidth is not None:
parameters['maxwidth'] = maxwidth
if hide_media is True:
parameters['hide_media'] = 'true'
if hide_thread is True:
parameters['hide_thread'] = 'true'
if omit_script is True:
parameters['omit_script'] = 'true'
if align is not None:
if align not in ('left', 'center', 'right', 'none'):
raise TwitterError({'message': "'align' must be 'left', 'center', 'right', or 'none'"})
parameters['align'] = align
if related:
if not isinstance(related, str):
raise TwitterError({'message': "'related' should be a string of comma separated screen names"})
parameters['related'] = related
if lang is not None:
if not isinstance(lang, str):
raise TwitterError({'message': "'lang' should be string instance"})
parameters['lang'] = lang
resp = self._RequestUrl(request_url, 'GET', data=parameters, enforce_auth=False)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data
def DestroyStatus(self, status_id, trim_user=False):
"""Destroys the status specified by the required ID parameter.
The authenticating user must be the author of the specified
status.
Args:
status_id (int):
The numerical ID of the status you're trying to destroy.
trim_user (bool, optional):
When set to True, each tweet returned in a timeline will include
a user object including only the status authors numerical ID.
Returns:
A twitter.Status instance representing the destroyed status message
"""
url = '%s/statuses/destroy/%s.json' % (self.base_url, status_id)
post_data = {
'id': enf_type('status_id', int, status_id),
'trim_user': enf_type('trim_user', bool, trim_user)
}
resp = self._RequestUrl(url, 'POST', data=post_data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def PostUpdate(self,
status,
media=None,
media_additional_owners=None,
media_category=None,
in_reply_to_status_id=None,
auto_populate_reply_metadata=False,
exclude_reply_user_ids=None,
latitude=None,
longitude=None,
place_id=None,
display_coordinates=False,
trim_user=False,
verify_status_length=True,
attachment_url=None):
"""Post a twitter status message from the authenticated user.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
Args:
status (str):
The message text to be posted. Must be less than or equal to 140
characters.
media (int, str, fp, optional):
A URL, a local file, or a file-like object (something with a
read() method), or a list of any combination of the above.
media_additional_owners (list, optional):
A list of user ids representing Twitter users that should be able
to use the uploaded media in their tweets. If you pass a list of
media, then additional_owners will apply to each object. If you
need more granular control, please use the UploadMedia* methods.
media_category (str, optional):
Only for use with the AdsAPI. See
https://dev.twitter.com/ads/creative/promoted-video-overview if
this applies to your application.
in_reply_to_status_id (int, optional):
The ID of an existing status that the status to be posted is
in reply to. This implicitly sets the in_reply_to_user_id
attribute of the resulting status to the user ID of the
message being replied to. Invalid/missing status IDs will be
ignored.
auto_populate_reply_metadata (bool, optional):
Automatically include the @usernames of the users mentioned or
participating in the tweet to which this tweet is in reply.
exclude_reply_user_ids (list, optional):
Remove given user_ids (*not* @usernames) from the tweet's
automatically generated reply metadata.
attachment_url (str, optional):
URL to an attachment resource: one to four photos, a GIF,
video, Quote Tweet, or DM deep link. If not specified and
media parameter is not None, we will attach the first media
object as the attachment URL. If a bad URL is passed, Twitter
will raise an error.
latitude (float, optional):
Latitude coordinate of the tweet in degrees. Will only work
in conjunction with longitude argument. Both longitude and
latitude will be ignored by twitter if the user has a false
geo_enabled setting.
longitude (float, optional):
Longitude coordinate of the tweet in degrees. Will only work
in conjunction with latitude argument. Both longitude and
latitude will be ignored by twitter if the user has a false
geo_enabled setting.
place_id (int, optional):
A place in the world. These IDs can be retrieved from
GET geo/reverse_geocode.
display_coordinates (bool, optional):
Whether or not to put a pin on the exact coordinates a tweet
has been sent from.
trim_user (bool, optional):
If True the returned payload will only contain the user IDs,
otherwise the payload will contain the full user data item.
verify_status_length (bool, optional):
If True, api throws a hard error that the status is over
140 characters. If False, Api will attempt to post the
status.
Returns:
(twitter.Status) A twitter.Status instance representing the
message posted.
"""
url = '%s/statuses/update.json' % self.base_url
if isinstance(status, str) or self._input_encoding is None:
u_status = status
else:
u_status = str(status, self._input_encoding)
if verify_status_length and calc_expected_status_length(u_status) > 140:
raise TwitterError("Text must be less than or equal to 140 characters.")
if auto_populate_reply_metadata and not in_reply_to_status_id:
raise TwitterError("If auto_populate_reply_metadata is True, you must set in_reply_to_status_id")
parameters = {
'status': u_status,
'in_reply_to_status_id': in_reply_to_status_id,
'auto_populate_reply_metadata': auto_populate_reply_metadata,
'place_id': place_id,
'display_coordinates': display_coordinates,
'trim_user': trim_user,
'exclude_reply_user_ids': ','.join([str(u) for u in exclude_reply_user_ids or []]),
}
if attachment_url:
parameters['attachment_url'] = attachment_url
if media:
chunked_types = ['video/mp4', 'video/quicktime', 'image/gif']
media_ids = []
if isinstance(media, (int, long)):
media_ids.append(media)
elif isinstance(media, list):
for media_file in media:
# If you want to pass just a media ID, it should be an int
if isinstance(media_file, (int, long)):
media_ids.append(media_file)
continue
_, _, file_size, media_type = parse_media_file(media_file)
if (media_type == 'image/gif' or media_type == 'video/mp4') and len(media) > 1:
raise TwitterError(
'You cannot post more than 1 GIF or 1 video in a single status.')
if file_size > self.chunk_size or media_type in chunked_types:
media_id = self.UploadMediaChunked(
media=media_file,
additional_owners=media_additional_owners,
media_category=media_category)
else:
media_id = self.UploadMediaSimple(
media=media_file,
additional_owners=media_additional_owners,
media_category=media_category)
media_ids.append(media_id)
else:
_, _, file_size, media_type = parse_media_file(media)
if file_size > self.chunk_size or media_type in chunked_types:
media_ids.append(self.UploadMediaChunked(media, media_additional_owners))
else:
media_ids.append(self.UploadMediaSimple(media, media_additional_owners))
parameters['media_ids'] = ','.join([str(mid) for mid in media_ids])
if latitude is not None and longitude is not None:
parameters['lat'] = str(latitude)
parameters['long'] = str(longitude)
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def UploadMediaSimple(self,
media,
additional_owners=None,
media_category=None):
""" Upload a media file to Twitter in one request. Used for small file
uploads that do not require chunked uploads.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at 100 by Twitter.
media_category:
Category with which to identify media upload. Only use with Ads
API & video files.
Returns:
media_id:
ID of the uploaded media returned by the Twitter API or 0.
"""
url = '%s/media/upload.json' % self.upload_url
parameters = {}
media_fp, _, _, _ = parse_media_file(media)
parameters['media'] = media_fp.read()
if additional_owners and len(additional_owners) > 100:
raise TwitterError({'message': 'Maximum of 100 additional owners may be specified for a Media object'})
if additional_owners:
parameters['additional_owners'] = additional_owners
if media_category:
parameters['media_category'] = media_category
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
try:
return data['media_id']
except KeyError:
raise TwitterError({'message': 'Media could not be uploaded.'})
def PostMediaMetadata(self,
media_id,
alt_text=None):
"""Provide addtional data for uploaded media.
Args:
media_id:
ID of a previously uploaded media item.
alt_text:
Image Alternate Text.
"""
url = '%s/media/metadata/create.json' % self.upload_url
parameters = {}
parameters['media_id'] = media_id
if alt_text:
parameters['alt_text'] = {"text": alt_text}
resp = self._RequestUrl(url, 'POST', json=parameters)
return resp
def _UploadMediaChunkedInit(self,
media,
additional_owners=None,
media_category=None):
"""Start a chunked upload to Twitter.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at 100 by Twitter.
media_category:
Category with which to identify media upload. Only use with Ads
API & video files.
Returns:
tuple: media_id (returned from Twitter), file-handler object (i.e., has .read()
method), filename media file.
"""
url = '%s/media/upload.json' % self.upload_url
media_fp, filename, file_size, media_type = parse_media_file(media)
if not all([media_fp, filename, file_size, media_type]):
raise TwitterError({'message': 'Could not process media file'})
parameters = {}
if additional_owners and len(additional_owners) > 100:
raise TwitterError({'message': 'Maximum of 100 additional owners may be specified for a Media object'})
if additional_owners:
parameters['additional_owners'] = additional_owners
if media_category:
parameters['media_category'] = media_category
# INIT doesn't read in any data. It's purpose is to prepare Twitter to
# receive the content in APPEND requests.
parameters['command'] = 'INIT'
parameters['media_type'] = media_type
parameters['total_bytes'] = file_size
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
try:
media_id = data['media_id']
except KeyError:
raise TwitterError({'message': 'Media could not be uploaded'})
return (media_id, media_fp, filename)
def _UploadMediaChunkedAppend(self,
media_id,
media_fp,
filename):
"""Appends (i.e., actually uploads) media file to Twitter.
Args:
media_id (int):
ID of the media file received from Init method.
media_fp (file):
File-like object representing media file (must have .read() method)
filename (str):
Filename of the media file being uploaded.
Returns:
True if successful. Raises otherwise.
"""
url = '%s/media/upload.json' % self.upload_url
boundary = "--{0}".format(uuid4().hex).encode('utf-8')
media_id_bytes = str(media_id).encode('utf-8')
headers = {'Content-Type': 'multipart/form-data; boundary={0}'.format(
boundary.decode('utf8')[2:]
)}
segment_id = 0
while True:
try:
data = media_fp.read(self.chunk_size)
except ValueError:
break
if not data:
break
body = [
boundary,
b'Content-Disposition: form-data; name="command"',
b'',
b'APPEND',
boundary,
b'Content-Disposition: form-data; name="media_id"',
b'',
media_id_bytes,
boundary,
b'Content-Disposition: form-data; name="segment_index"',
b'',
str(segment_id).encode('utf-8'),
boundary,
'Content-Disposition: form-data; name="media"; filename="{0!r}"'.format(filename).encode('utf8'),
b'Content-Type: application/octet-stream',
b'',
data,
boundary + b'--'
]
body_data = b'\r\n'.join(body)
headers['Content-Length'] = str(len(body_data))
resp = self._RequestChunkedUpload(url=url,
headers=headers,
data=body_data)
# The body of the response should be blank, but the normal decoding
# raises a JSONDecodeError, so we should only do error checking
# if the response is not blank.
if resp.content.decode('utf-8'):
return self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
segment_id += 1
try:
media_fp.close()
except Exception as e:
pass
return True
def _UploadMediaChunkedFinalize(self, media_id):
"""Finalize chunked upload to Twitter.
Args:
media_id (int):
ID of the media file for which to finalize the upload.
Returns:
json: JSON string of data from Twitter.
"""
url = '%s/media/upload.json' % self.upload_url
parameters = {
'command': 'FINALIZE',
'media_id': media_id
}
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data
def UploadMediaChunked(self,
media,
additional_owners=None,
media_category=None):
"""Upload a media file to Twitter in multiple requests.
Args:
media:
File-like object to upload.
additional_owners: additional Twitter users that are allowed to use
The uploaded media. Should be a list of integers. Maximum
number of additional owners is capped at 100 by Twitter.
media_category:
Category with which to identify media upload. Only use with Ads
API & video files.
Returns:
media_id:
ID of the uploaded media returned by the Twitter API. Raises if
unsuccesful.
"""
media_id, media_fp, filename = self._UploadMediaChunkedInit(media=media,
additional_owners=additional_owners,
media_category=media_category)
append = self._UploadMediaChunkedAppend(media_id=media_id,
media_fp=media_fp,
filename=filename)
if not append:
TwitterError('Media could not be uploaded.')
data = self._UploadMediaChunkedFinalize(media_id)
try:
return data['media_id']
except KeyError:
raise TwitterError('Media could not be uploaded.')
def PostMedia(self,
status,
media,
possibly_sensitive=None,
in_reply_to_status_id=None,
latitude=None,
longitude=None,
place_id=None,
display_coordinates=False):
"""Post a twitter status message from the user with a picture attached.
Args:
status:
the text of your update
media:
This can be the location of media(PNG, JPG, GIF) on the local file
system or at an HTTP URL, it can also be a file-like object
possibly_sensitive:
set true if content is "advanced." [Optional]
in_reply_to_status_id:
ID of a status that this is in reply to. [Optional]
lat:
latitude of location. [Optional]
long:
longitude of location. [Optional]
place_id:
A place in the world identified by a Twitter place ID. [Optional]
display_coordinates:
Set true if you want to display coordinates. [Optional]
Returns:
A twitter.Status instance representing the message posted.
"""
warnings.warn((
"This endpoint has been deprecated by Twitter. Please use "
"PostUpdate() instead. Details of Twitter's deprecation can be "
"found at: "
"dev.twitter.com/rest/reference/post/statuses/update_with_media"),
PythonTwitterDeprecationWarning330)
url = '%s/statuses/update_with_media.json' % self.base_url
if isinstance(status, str) or self._input_encoding is None:
u_status = status
else:
u_status = str(status, self._input_encoding)
data = {'status': u_status}
if not hasattr(media, 'read'):
if media.startswith('http'):
data['media'] = urlopen(media).read()
else:
with open(str(media), 'rb') as f:
data['media'] = f.read()
else:
data['media'] = media.read()
if possibly_sensitive:
data['possibly_sensitive'] = 'true'
if in_reply_to_status_id:
data['in_reply_to_status_id'] = str(in_reply_to_status_id)
if latitude is not None and longitude is not None:
data['lat'] = str(latitude)
data['long'] = str(longitude)
if place_id is not None:
data['place_id'] = str(place_id)
if display_coordinates:
data['display_coordinates'] = 'true'
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def PostMultipleMedia(self, status, media, possibly_sensitive=None,
in_reply_to_status_id=None, latitude=None,
longitude=None, place_id=None,
display_coordinates=False):
"""
Post a twitter status message from the authenticated user with
multiple pictures attached.
Args:
status:
the text of your update
media:
location of multiple media elements(PNG, JPG, GIF)
possibly_sensitive:
set true is content is "advanced"
in_reply_to_status_id:
ID of a status that this is in reply to
lat:
location in latitude
long:
location in longitude
place_id:
A place in the world identified by a Twitter place ID
display_coordinates:
Returns:
A twitter.Status instance representing the message posted.
"""
warnings.warn((
"This method is deprecated. Please use PostUpdate instead, "
"passing a list of media that you would like to associate "
"with the update."), PythonTwitterDeprecationWarning330)
if type(media) is not list:
raise TwitterError("Must by multiple media elements")
if media.__len__() > 4:
raise TwitterError("Maximum of 4 media elements can be allocated to a tweet")
url = '%s/media/upload.json' % self.upload_url
if isinstance(status, str) or self._input_encoding is None:
u_status = status
else:
u_status = str(status, self._input_encoding)
media_ids = ''
for m in range(0, len(media)):
data = {}
if not hasattr(media[m], 'read'):
if media[m].startswith('http'):
data['media'] = urlopen(media[m]).read()
else:
data['media'] = open(str(media[m]), 'rb').read()
else:
data['media'] = media[m].read()
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
media_ids += str(data['media_id_string'])
if m is not len(media) - 1:
media_ids += ","
data = {'status': u_status, 'media_ids': media_ids}
url = '%s/statuses/update.json' % self.base_url
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def _TweetTextWrap(self,
status,
char_lim=140):
if not self._config:
self.GetHelpConfiguration()
tweets = []
line = []
line_length = 0
words = re.split(r'\s', status)
if len(words) == 1 and not is_url(words[0]):
if len(words[0]) > 140:
raise TwitterError({"message": "Unable to split status into tweetable parts. Word was: {0}/{1}".format(len(words[0]), char_lim)})
else:
tweets.append(words[0])
return tweets
for word in words:
if len(word) > char_lim:
raise TwitterError({"message": "Unable to split status into tweetable parts. Word was: {0}/{1}".format(len(word), char_lim)})
new_len = line_length
if is_url(word):
new_len = line_length + self._config['short_url_length_https'] + 1
else:
new_len += len(word) + 1
if new_len > 140:
tweets.append(' '.join(line))
line = [word]
line_length = new_len - line_length
else:
line.append(word)
line_length = new_len
tweets.append(' '.join(line))
return tweets
def PostUpdates(self,
status,
continuation=None,
**kwargs):
"""Post one or more twitter status messages from the authenticated user.
Unlike api.PostUpdate, this method will post multiple status updates
if the message is longer than 140 characters.
Args:
status:
The message text to be posted.
May be longer than 140 characters.
continuation:
The character string, if any, to be appended to all but the
last message. Note that Twitter strips trailing '...' strings
from messages. Consider using the unicode \u2026 character
(horizontal ellipsis) instead. [Defaults to None]
**kwargs:
See api.PostUpdate for a list of accepted parameters.
Returns:
A of list twitter.Status instance representing the messages posted.
"""
results = list()
if continuation is None:
continuation = ''
char_limit = CHARACTER_LIMIT - len(continuation)
tweets = self._TweetTextWrap(status=status, char_lim=char_limit)
if len(tweets) == 1:
results.append(self.PostUpdate(status=tweets[0], **kwargs))
return results
for tweet in tweets[0:-1]:
results.append(self.PostUpdate(status=tweet + continuation, **kwargs))
results.append(self.PostUpdate(status=tweets[-1], **kwargs))
return results
def PostRetweet(self, status_id, trim_user=False):
"""Retweet a tweet with the Retweet API.
Args:
status_id:
The numerical id of the tweet that will be retweeted
trim_user:
If True the returned payload will only contain the user IDs,
otherwise the payload will contain the full user data item.
[Optional]
Returns:
A twitter.Status instance representing the original tweet with retweet details embedded.
"""
try:
if int(status_id) <= 0:
raise TwitterError({'message': "'status_id' must be a positive number"})
except ValueError:
raise TwitterError({'message': "'status_id' must be an integer"})
url = '%s/statuses/retweet/%s.json' % (self.base_url, status_id)
data = {'id': status_id}
if trim_user:
data['trim_user'] = 'true'
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def GetUserRetweets(self,
count=None,
since_id=None,
max_id=None,
trim_user=False):
"""Fetch the sequence of retweets made by the authenticated user.
Args:
count:
The number of status messages to retrieve. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
trim_user:
If True the returned payload will only contain the user IDs,
otherwise the payload will contain the full user data item.
[Optional]
Returns:
A sequence of twitter.Status instances, one for each message up to count
"""
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user,
exclude_replies=True, include_rts=True)
def GetReplies(self,
since_id=None,
count=None,
max_id=None,
trim_user=False):
"""Get a sequence of status messages representing the 20 most
recent replies (status updates prefixed with @twitterID) to the
authenticating user.
Args:
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
trim_user:
If True the returned payload will only contain the user IDs,
otherwise the payload will contain the full user data item.
[Optional]
Returns:
A sequence of twitter.Status instances, one for each reply to the user.
"""
return self.GetUserTimeline(since_id=since_id, count=count, max_id=max_id, trim_user=trim_user,
exclude_replies=False, include_rts=False)
def GetRetweets(self,
statusid,
count=None,
trim_user=False):
"""Returns up to 100 of the first retweets of the tweet identified
by statusid
Args:
statusid (int):
The ID of the tweet for which retweets should be searched for
count (int, optional):
The number of status messages to retrieve.
trim_user (bool, optional):
If True the returned payload will only contain the user IDs,
otherwise the payload will contain the full user data item.
Returns:
A list of twitter.Status instances, which are retweets of statusid
"""
url = '%s/statuses/retweets/%s.json' % (self.base_url, statusid)
parameters = {
'trim_user': enf_type('trim_user', bool, trim_user),
}
if count:
parameters['count'] = enf_type('count', int, count)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(s) for s in data]
def GetRetweeters(self,
status_id,
cursor=None,
count=100,
stringify_ids=False):
"""Returns a collection of up to 100 user IDs belonging to users who have
retweeted the tweet specified by the status_id parameter.
Args:
status_id:
the tweet's numerical ID
cursor:
breaks the ids into pages of no more than 100.
stringify_ids:
returns the IDs as unicode strings. [Optional]
Returns:
A list of user IDs
"""
url = '%s/statuses/retweeters/ids.json' % (self.base_url)
parameters = {
'id': enf_type('id', int, status_id),
'stringify_ids': enf_type('stringify_ids', bool, stringify_ids)
}
result = []
total_count = 0
while True:
if cursor:
try:
parameters['cursor'] = int(cursor)
except ValueError:
raise TwitterError({'message': "cursor must be an integer"})
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
result += [x for x in data['ids']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
total_count -= len(data['ids'])
if total_count < 1:
break
else:
break
return result
def GetRetweetsOfMe(self,
count=None,
since_id=None,
max_id=None,
trim_user=False,
include_entities=True,
include_user_entities=True):
"""Returns up to 100 of the most recent tweets of the user that have been
retweeted by others.
Args:
count:
The number of retweets to retrieve, up to 100.
Defaults to 20. [Optional]
since_id:
Returns results with an ID greater than
(newer than) this ID. [Optional]
max_id:
Returns results with an ID less than or equal
to this ID. [Optional]
trim_user:
When True, the user object for each tweet will
only be an ID. [Optional]
include_entities:
When True, the tweet entities will be included. [Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
"""
url = '%s/statuses/retweets_of_me.json' % self.base_url
parameters = {}
if count is not None:
try:
if int(count) > 100:
raise TwitterError({'message': "'count' may not be greater than 100"})
except ValueError:
raise TwitterError({'message': "'count' must be an integer"})
if count:
parameters['count'] = count
if since_id:
parameters['since_id'] = since_id
if max_id:
parameters['max_id'] = max_id
if trim_user:
parameters['trim_user'] = trim_user
if not include_entities:
parameters['include_entities'] = include_entities
if not include_user_entities:
parameters['include_user_entities'] = include_user_entities
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(s) for s in data]
def _GetBlocksMutesPaged(self,
endpoint,
action,
cursor=-1,
skip_status=False,
include_entities=False,
stringify_ids=False):
""" Fetch a page of the users (as twitter.User instances)
blocked or muted by the currently authenticated user.
Args:
endpoint (str):
Either "mute" or "block".
action (str):
Either 'list' or 'ids' depending if you want to return fully-hydrated
twitter.User objects or a list of user IDs as ints.
cursor (int, optional):
Should be set to -1 if you want the first page, thereafter denotes
the page of users that you want to return.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
When True, the user entities will be included.
Returns:
next_cursor, previous_cursor, list of twitter.User instances,
one for each user.
"""
urls = {
'mute': {
'list': '%s/mutes/users/list.json' % self.base_url,
'ids': '%s/mutes/users/ids.json' % self.base_url
},
'block': {
'list': '%s/blocks/list.json' % self.base_url,
'ids': '%s/blocks/ids.json' % self.base_url
}
}
url = urls[endpoint][action]
result = []
parameters = {}
if skip_status:
parameters['skip_status'] = True
if include_entities:
parameters['include_entities'] = True
parameters['cursor'] = cursor
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
if action == 'ids':
result += data.get('ids')
else:
result += [User.NewFromJsonDict(x) for x in data['users']]
next_cursor = data.get('next_cursor', 0)
previous_cursor = data.get('previous_cursor', 0)
return next_cursor, previous_cursor, result
def GetBlocks(self,
skip_status=False,
include_entities=False):
""" Fetch the sequence of all users (as twitter.User instances),
blocked by the currently authenticated user.
Args:
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
When True, the user entities will be included.
Returns:
A list of twitter.User instances, one for each blocked user.
"""
result = []
cursor = -1
while True:
next_cursor, previous_cursor, users = self.GetBlocksPaged(
cursor=cursor,
skip_status=skip_status,
include_entities=include_entities)
result += users
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def GetBlocksPaged(self,
cursor=-1,
skip_status=False,
include_entities=False):
""" Fetch a page of the users (as twitter.User instances)
blocked by the currently authenticated user.
Args:
cursor (int, optional):
Should be set to -1 if you want the first page, thereafter denotes
the page of blocked users that you want to return.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
When True, the user entities will be included.
Returns:
next_cursor, previous_cursor, list of twitter.User instances,
one for each blocked user.
"""
return self._GetBlocksMutesPaged(endpoint='block',
action='list',
cursor=cursor,
skip_status=skip_status,
include_entities=include_entities)
def GetBlocksIDs(self,
stringify_ids=False):
"""Fetch the sequence of all user IDs blocked by the
currently authenticated user.
Args:
stringify_ids (bool, optional):
If True user IDs will be returned as strings rather than integers.
Returns:
A list of user IDs for all blocked users.
"""
result = []
cursor = -1
while True:
next_cursor, previous_cursor, user_ids = self.GetBlocksIDsPaged(
cursor=cursor,
stringify_ids=stringify_ids)
result += user_ids
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def GetBlocksIDsPaged(self,
cursor=-1,
stringify_ids=False):
""" Fetch a page of the user IDs blocked by the currently
authenticated user.
Args:
cursor (int, optional):
Should be set to -1 if you want the first page, thereafter denotes
the page of blocked users that you want to return.
stringify_ids (bool, optional):
If True user IDs will be returned as strings rather than integers.
Returns:
next_cursor, previous_cursor, list of user IDs of blocked users.
"""
return self._GetBlocksMutesPaged(endpoint='block',
action='ids',
cursor=cursor,
stringify_ids=False)
def GetMutes(self,
skip_status=False,
include_entities=False):
""" Fetch the sequence of all users (as twitter.User instances),
muted by the currently authenticated user.
Args:
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
When True, the user entities will be included.
Returns:
A list of twitter.User instances, one for each muted user.
"""
result = []
cursor = -1
while True:
next_cursor, previous_cursor, users = self.GetMutesPaged(
cursor=cursor,
skip_status=skip_status,
include_entities=include_entities)
result += users
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def GetMutesPaged(self,
cursor=-1,
skip_status=False,
include_entities=False):
""" Fetch a page of the users (as twitter.User instances)
muted by the currently authenticated user.
Args:
cursor (int, optional):
Should be set to -1 if you want the first page, thereafter denotes
the page of muted users that you want to return.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
When True, the user entities will be included.
Returns:
next_cursor, previous_cursor, list of twitter.User instances,
one for each muted user.
"""
return self._GetBlocksMutesPaged(endpoint='mute',
action='list',
cursor=cursor,
skip_status=skip_status,
include_entities=include_entities)
def GetMutesIDs(self,
stringify_ids=False):
"""Fetch the sequence of all user IDs muted by the
currently authenticated user.
Args:
stringify_ids (bool, optional):
If True user IDs will be returned as strings rather than integers.
Returns:
A list of user IDs for all muted users.
"""
result = []
cursor = -1
while True:
next_cursor, previous_cursor, user_ids = self.GetMutesIDsPaged(
cursor=cursor,
stringify_ids=stringify_ids)
result += user_ids
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def GetMutesIDsPaged(self,
cursor=-1,
stringify_ids=False):
""" Fetch a page of the user IDs muted by the currently
authenticated user.
Args:
cursor (int, optional):
Should be set to -1 if you want the first page, thereafter denotes
the page of muted users that you want to return.
stringify_ids (bool, optional):
If True user IDs will be returned as strings rather than integers.
Returns:
next_cursor, previous_cursor, list of user IDs of muted users.
"""
return self._GetBlocksMutesPaged(endpoint='mute',
action='ids',
cursor=cursor,
stringify_ids=stringify_ids)
def _BlockMute(self,
action,
endpoint,
user_id=None,
screen_name=None,
include_entities=True,
skip_status=False):
"""Create or destroy a block or mute on behalf of the authenticated user.
Args:
action (str):
Either 'create' or 'destroy'.
endpoint (str):
Either 'block' or 'mute'.
user_id (int, optional)
The numerical ID of the user to block/mute.
screen_name (str, optional):
The screen name of the user to block/mute.
include_entities (bool, optional):
The entities node will not be included if set to False.
skip_status (bool, optional):
When set to False, the blocked User's statuses will not be included
with the returned User object.
Returns:
twitter.User: twitter.User object representing the blocked/muted user.
"""
urls = {
'block': {
'create': '%s/blocks/create.json' % (self.base_url),
'destroy': '%s/blocks/destroy.json' % (self.base_url),
},
'mute': {
'create': '%s/mutes/users/create.json' % (self.base_url),
'destroy': '%s/mutes/users/destroy.json' % (self.base_url)
}
}
url = urls[endpoint][action]
post_data = {}
if user_id:
post_data['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
post_data['screen_name'] = screen_name
else:
raise TwitterError("You must specify either a user_id or screen_name")
if include_entities:
post_data['include_entities'] = enf_type('include_entities', bool, include_entities)
if skip_status:
post_data['skip_status'] = enf_type('skip_status', bool, skip_status)
resp = self._RequestUrl(url, 'POST', data=post_data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def CreateBlock(self,
user_id=None,
screen_name=None,
include_entities=True,
skip_status=False):
"""Blocks the user specified by either user_id or screen_name.
Args:
user_id (int, optional)
The numerical ID of the user to block.
screen_name (str, optional):
The screen name of the user to block.
include_entities (bool, optional):
The entities node will not be included if set to False.
skip_status (bool, optional):
When set to False, the blocked User's statuses will not be included
with the returned User object.
Returns:
A twitter.User instance representing the blocked user.
"""
return self._BlockMute(action='create',
endpoint='block',
user_id=user_id,
screen_name=screen_name,
include_entities=include_entities,
skip_status=skip_status)
def DestroyBlock(self,
user_id=None,
screen_name=None,
include_entities=True,
skip_status=False):
"""Unlocks the user specified by either user_id or screen_name.
Args:
user_id (int, optional)
The numerical ID of the user to block.
screen_name (str, optional):
The screen name of the user to block.
include_entities (bool, optional):
The entities node will not be included if set to False.
skip_status (bool, optional):
When set to False, the blocked User's statuses will not be included
with the returned User object.
Returns:
A twitter.User instance representing the blocked user.
"""
return self._BlockMute(action='destroy',
endpoint='block',
user_id=user_id,
screen_name=screen_name,
include_entities=include_entities,
skip_status=skip_status)
def CreateMute(self,
user_id=None,
screen_name=None,
include_entities=True,
skip_status=False):
"""Mutes the user specified by either user_id or screen_name.
Args:
user_id (int, optional)
The numerical ID of the user to mute.
screen_name (str, optional):
The screen name of the user to mute.
include_entities (bool, optional):
The entities node will not be included if set to False.
skip_status (bool, optional):
When set to False, the muted User's statuses will not be included
with the returned User object.
Returns:
A twitter.User instance representing the muted user.
"""
return self._BlockMute(action='create',
endpoint='mute',
user_id=user_id,
screen_name=screen_name,
include_entities=include_entities,
skip_status=skip_status)
def DestroyMute(self,
user_id=None,
screen_name=None,
include_entities=True,
skip_status=False):
"""Unlocks the user specified by either user_id or screen_name.
Args:
user_id (int, optional)
The numerical ID of the user to mute.
screen_name (str, optional):
The screen name of the user to mute.
include_entities (bool, optional):
The entities node will not be included if set to False.
skip_status (bool, optional):
When set to False, the muted User's statuses will not be included
with the returned User object.
Returns:
A twitter.User instance representing the muted user.
"""
return self._BlockMute(action='destroy',
endpoint='mute',
user_id=user_id,
screen_name=screen_name,
include_entities=include_entities,
skip_status=skip_status)
def _GetIDsPaged(self,
url,
user_id,
screen_name,
cursor,
stringify_ids,
count):
"""
This is the lowest level paging logic for fetching IDs. It is used
solely by GetFollowerIDsPaged and GetFriendIDsPaged. It is not intended
for other use.
See GetFollowerIDsPaged or GetFriendIDsPaged for an explanation of the
input arguments.
"""
result = []
parameters = {}
if user_id is not None:
parameters['user_id'] = user_id
if screen_name is not None:
parameters['screen_name'] = screen_name
if count is not None:
parameters['count'] = count
parameters['stringify_ids'] = stringify_ids
parameters['cursor'] = cursor
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
if 'ids' in data:
result.extend([x for x in data['ids']])
next_cursor = data.get('next_cursor', 0)
previous_cursor = data.get('previous_cursor', 0)
return next_cursor, previous_cursor, result
def GetFollowerIDsPaged(self,
user_id=None,
screen_name=None,
cursor=-1,
stringify_ids=False,
count=5000):
"""Make a cursor driven call to return a list of one page followers.
The caller is responsible for handling the cursor value and looping
to gather all of the data
Args:
user_id:
The twitter id of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
stringify_ids:
if True then twitter will return the ids as strings instead of
integers. [Optional]
count:
The number of user id's to retrieve per API request. Please be aware
that this might get you rate-limited if set to a small number.
By default Twitter will retrieve 5000 UIDs per call. [Optional]
Returns:
next_cursor, previous_cursor, data sequence of user ids,
one for each follower
"""
url = '%s/followers/ids.json' % self.base_url
return self._GetIDsPaged(url=url,
user_id=user_id,
screen_name=screen_name,
cursor=cursor,
stringify_ids=stringify_ids,
count=count)
def GetFriendIDsPaged(self,
user_id=None,
screen_name=None,
cursor=-1,
stringify_ids=False,
count=5000):
"""Make a cursor driven call to return the list of all friends
The caller is responsible for handling the cursor value and looping
to gather all of the data
Args:
user_id:
The twitter id of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
stringify_ids:
if True then twitter will return the ids as strings instead of
integers. [Optional]
count:
The number of user id's to retrieve per API request. Please be aware
that this might get you rate-limited if set to a small number.
By default Twitter will retrieve 5000 UIDs per call. [Optional]
Returns:
next_cursor, previous_cursor, data sequence of twitter.User instances,
one for each friend
"""
url = '%s/friends/ids.json' % self.base_url
return self._GetIDsPaged(url,
user_id,
screen_name,
cursor,
stringify_ids,
count)
def _GetFriendFollowerIDs(self,
url=None,
user_id=None,
screen_name=None,
cursor=None,
count=None,
stringify_ids=False,
total_count=None):
""" Common method for GetFriendIDs and GetFollowerIDs """
count = 5000
cursor = -1
result = []
if total_count:
total_count = enf_type('total_count', int, total_count)
if total_count and total_count < count:
count = total_count
while True:
if total_count is not None and len(result) + count > total_count:
break
next_cursor, previous_cursor, data = self._GetIDsPaged(
url=url,
user_id=user_id,
screen_name=screen_name,
cursor=cursor,
stringify_ids=stringify_ids,
count=count)
result.extend([x for x in data])
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def GetFollowerIDs(self,
user_id=None,
screen_name=None,
cursor=None,
stringify_ids=False,
count=None,
total_count=None):
"""Returns a list of twitter user id's for every person
that is following the specified user.
Args:
user_id:
The id of the user to retrieve the id list for. [Optional]
screen_name:
The screen_name of the user to retrieve the id list for. [Optional]
cursor:
Specifies the Twitter API Cursor location to start at.
Note: there are pagination limits. [Optional]
stringify_ids:
if True then twitter will return the ids as strings instead of
integers. [Optional]
count:
The number of user id's to retrieve per API request. Please be aware
that this might get you rate-limited if set to a small number.
By default Twitter will retrieve 5000 UIDs per call. [Optional]
total_count:
The total amount of UIDs to retrieve. Good if the account has many
followers and you don't want to get rate limited. The data returned
might contain more UIDs if total_count is not a multiple of count
(5000 by default). [Optional]
Returns:
A list of integers, one for each user id.
"""
url = '%s/followers/ids.json' % self.base_url
return self._GetFriendFollowerIDs(url=url,
user_id=user_id,
screen_name=screen_name,
cursor=cursor,
stringify_ids=stringify_ids,
count=count,
total_count=total_count)
def GetFriendIDs(self,
user_id=None,
screen_name=None,
cursor=None,
count=None,
stringify_ids=False,
total_count=None):
""" Fetch a sequence of user ids, one for each friend.
Returns a list of all the given user's friends' IDs. If no user_id or
screen_name is given, the friends will be those of the authenticated
user.
Args:
user_id:
The id of the user to retrieve the id list for. [Optional]
screen_name:
The screen_name of the user to retrieve the id list for. [Optional]
cursor:
Specifies the Twitter API Cursor location to start at.
Note: there are pagination limits. [Optional]
stringify_ids:
if True then twitter will return the ids as strings instead of integers.
[Optional]
count:
The number of user id's to retrieve per API request. Please be aware that
this might get you rate-limited if set to a small number.
By default Twitter will retrieve 5000 UIDs per call. [Optional]
total_count:
The total amount of UIDs to retrieve. Good if the account has many followers
and you don't want to get rate limited. The data returned might contain more
UIDs if total_count is not a multiple of count (5000 by default). [Optional]
Returns:
A list of integers, one for each user id.
"""
url = '%s/friends/ids.json' % self.base_url
return self._GetFriendFollowerIDs(url,
user_id,
screen_name,
cursor,
count,
stringify_ids,
total_count)
def _GetFriendsFollowersPaged(self,
url=None,
user_id=None,
screen_name=None,
cursor=-1,
count=200,
skip_status=False,
include_user_entities=True):
"""Make a cursor driven call to return the list of 1 page of friends
or followers.
Args:
url:
Endpoint from which to get data. Either
base_url+'/followers/list.json' or base_url+'/friends/list.json'.
user_id:
The twitter id of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a maximum of 200.
Defaults to 200. [Optional]
skip_status:
If True the statuses will not be returned in the user items.
[Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
next_cursor, previous_cursor, data sequence of twitter.User
instances, one for each follower
"""
if user_id and screen_name:
warnings.warn(
"If both user_id and screen_name are specified, Twitter will "
"return the followers of the user specified by screen_name, "
"however this behavior is undocumented by Twitter and might "
"change without warning.", stacklevel=2)
parameters = {}
if user_id is not None:
parameters['user_id'] = user_id
if screen_name is not None:
parameters['screen_name'] = screen_name
try:
parameters['count'] = int(count)
except ValueError:
raise TwitterError({'message': "count must be an integer"})
parameters['skip_status'] = skip_status
parameters['include_user_entities'] = include_user_entities
parameters['cursor'] = cursor
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
if 'users' in data:
users = [User.NewFromJsonDict(user) for user in data['users']]
else:
users = []
if 'next_cursor' in data:
next_cursor = data['next_cursor']
else:
next_cursor = 0
if 'previous_cursor' in data:
previous_cursor = data['previous_cursor']
else:
previous_cursor = 0
return next_cursor, previous_cursor, users
def GetFollowersPaged(self,
user_id=None,
screen_name=None,
cursor=-1,
count=200,
skip_status=False,
include_user_entities=True):
"""Make a cursor driven call to return the list of all followers
Args:
user_id:
The twitter id of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a maximum of 200.
Defaults to 200. [Optional]
skip_status:
If True the statuses will not be returned in the user items.
[Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
next_cursor, previous_cursor, data sequence of twitter.User
instances, one for each follower
"""
url = '%s/followers/list.json' % self.base_url
return self._GetFriendsFollowersPaged(url,
user_id,
screen_name,
cursor,
count,
skip_status,
include_user_entities)
def GetFriendsPaged(self,
user_id=None,
screen_name=None,
cursor=-1,
count=200,
skip_status=False,
include_user_entities=True):
"""Make a cursor driven call to return the list of all friends.
Args:
user_id:
The twitter id of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a current maximum of
200. Defaults to 200. [Optional]
skip_status:
If True the statuses will not be returned in the user items.
[Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
next_cursor, previous_cursor, data sequence of twitter.User
instances, one for each follower
"""
url = '%s/friends/list.json' % self.base_url
return self._GetFriendsFollowersPaged(url,
user_id,
screen_name,
cursor,
count,
skip_status,
include_user_entities)
def _GetFriendsFollowers(self,
url=None,
user_id=None,
screen_name=None,
cursor=None,
count=None,
total_count=None,
skip_status=False,
include_user_entities=True):
""" Fetch the sequence of twitter.User instances, one for each friend
or follower.
Args:
url:
URL to get. Either base_url + ('/followers/list.json' or
'/friends/list.json').
user_id:
The twitter id of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a maximum of 200.
Defaults to 200. [Optional]
total_count:
The upper bound of number of users to return, defaults to None.
skip_status:
If True the statuses will not be returned in the user items.
[Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
A sequence of twitter.User instances, one for each friend or follower
"""
if cursor is not None or count is not None:
warnings.warn(
"Use of 'cursor' and 'count' parameters are deprecated as of "
"python-twitter 3.0. Please use GetFriendsPaged or "
"GetFollowersPaged instead.",
PythonTwitterDeprecationWarning330)
count = 200
cursor = -1
result = []
if total_count:
try:
total_count = int(total_count)
except ValueError:
raise TwitterError({'message': "total_count must be an integer"})
if total_count <= 200:
count = total_count
while True:
if total_count is not None and len(result) + count > total_count:
break
next_cursor, previous_cursor, data = self._GetFriendsFollowersPaged(
url,
user_id,
screen_name,
cursor,
count,
skip_status,
include_user_entities)
if next_cursor:
cursor = next_cursor
result.extend(data)
if next_cursor == 0 or next_cursor == previous_cursor:
break
return result
def GetFollowers(self,
user_id=None,
screen_name=None,
cursor=None,
count=None,
total_count=None,
skip_status=False,
include_user_entities=True):
"""Fetch the sequence of twitter.User instances, one for each follower.
If both user_id and screen_name are specified, this call will return
the followers of the user specified by screen_name, however this
behavior is undocumented by Twitter and may change without warning.
Args:
user_id:
The twitter id of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose followers you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a maximum of 200.
Defaults to 200. [Optional]
total_count:
The upper bound of number of users to return, defaults to None.
skip_status:
If True the statuses will not be returned in the user items. [Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
A sequence of twitter.User instances, one for each follower
"""
url = '%s/followers/list.json' % self.base_url
return self._GetFriendsFollowers(url,
user_id,
screen_name,
cursor,
count,
total_count,
skip_status,
include_user_entities)
def GetFriends(self,
user_id=None,
screen_name=None,
cursor=None,
count=None,
total_count=None,
skip_status=False,
include_user_entities=True):
"""Fetch the sequence of twitter.User instances, one for each friend.
If both user_id and screen_name are specified, this call will return
the followers of the user specified by screen_name, however this
behavior is undocumented by Twitter and may change without warning.
Args:
user_id:
The twitter id of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
screen_name:
The twitter name of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
cursor:
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
count:
The number of users to return per page, up to a maximum of 200.
Defaults to 200. [Optional]
total_count:
The upper bound of number of users to return, defaults to None.
skip_status:
If True the statuses will not be returned in the user items.
[Optional]
include_user_entities:
When True, the user entities will be included. [Optional]
Returns:
A sequence of twitter.User instances, one for each friend
"""
url = '%s/friends/list.json' % self.base_url
return self._GetFriendsFollowers(url,
user_id,
screen_name,
cursor,
count,
total_count,
skip_status,
include_user_entities)
def UsersLookup(self,
user_id=None,
screen_name=None,
users=None,
include_entities=True):
"""Fetch extended information for the specified users.
Users may be specified either as lists of either user_ids,
screen_names, or twitter.User objects. The list of users that
are queried is the union of all specified parameters.
Args:
user_id (int, list, optional):
A list of user_ids to retrieve extended information.
screen_name (str, optional):
A list of screen_names to retrieve extended information.
users (list, optional):
A list of twitter.User objects to retrieve extended information.
include_entities (bool, optional):
The entities node that may appear within embedded statuses will be
excluded when set to False.
Returns:
A list of twitter.User objects for the requested users
"""
if not any([user_id, screen_name, users]):
raise TwitterError("Specify at least one of user_id, screen_name, or users.")
url = '%s/users/lookup.json' % self.base_url
parameters = {
'include_entities': include_entities
}
uids = list()
if user_id:
uids.extend(user_id)
if users:
uids.extend([u.id for u in users])
if len(uids):
parameters['user_id'] = ','.join([str(u) for u in uids])
if screen_name:
parameters['screen_name'] = ','.join(screen_name)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [User.NewFromJsonDict(u) for u in data]
def GetUser(self,
user_id=None,
screen_name=None,
include_entities=True):
"""Returns a single user.
Args:
user_id (int, optional):
The id of the user to retrieve.
screen_name (str, optional):
The screen name of the user for whom to return results for.
Either a user_id or screen_name is required for this method.
include_entities (bool, optional):
The entities node will be omitted when set to False.
Returns:
A twitter.User instance representing that user
"""
url = '%s/users/show.json' % (self.base_url)
parameters = {
'include_entities': include_entities
}
if user_id:
parameters['user_id'] = user_id
elif screen_name:
parameters['screen_name'] = screen_name
else:
raise TwitterError("Specify at least one of user_id or screen_name.")
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def GetDirectMessages(self,
since_id=None,
max_id=None,
count=None,
include_entities=True,
skip_status=False,
full_text=False,
page=None):
"""Returns a list of the direct messages sent to the authenticating user.
Args:
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
count:
Specifies the number of direct messages to try and retrieve, up to a
maximum of 200. The value of count is best thought of as a limit to the
number of Tweets to return because suspended or deleted content is
removed after the count has been applied. [Optional]
include_entities:
The entities node will be omitted when set to False.
[Optional]
skip_status:
When set to True statuses will not be included in the returned user
objects. [Optional]
full_text:
When set to True full message will be included in the returned message
object if message length is bigger than 140 characters. [Optional]
page:
If you want more than 200 messages, you can use this and get 20 messages
each time. You must recall it and increment the page value until it
return nothing. You can't use count option with it. First value is 1 and
not 0.
Returns:
A sequence of twitter.DirectMessage instances
"""
url = '%s/direct_messages.json' % self.base_url
parameters = {}
if since_id:
parameters['since_id'] = since_id
if max_id:
parameters['max_id'] = max_id
if count:
try:
parameters['count'] = int(count)
except ValueError:
raise TwitterError({'message': "count must be an integer"})
if not include_entities:
parameters['include_entities'] = 'false'
if skip_status:
parameters['skip_status'] = 1
if full_text:
parameters['full_text'] = 'true'
if page:
parameters['page'] = page
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [DirectMessage.NewFromJsonDict(x) for x in data]
def GetSentDirectMessages(self,
since_id=None,
max_id=None,
count=None,
page=None,
include_entities=True):
"""Returns a list of the direct messages sent by the authenticating user.
Args:
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occured since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
count:
Specifies the number of direct messages to try and retrieve, up to a
maximum of 200. The value of count is best thought of as a limit to the
number of Tweets to return because suspended or deleted content is
removed after the count has been applied. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
include_entities:
The entities node will be omitted when set to False.
[Optional]
Returns:
A sequence of twitter.DirectMessage instances
"""
url = '%s/direct_messages/sent.json' % self.base_url
parameters = {}
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
if max_id:
parameters['max_id'] = max_id
if count:
try:
parameters['count'] = int(count)
except ValueError:
raise TwitterError({'message': "count must be an integer"})
if not include_entities:
parameters['include_entities'] = 'false'
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [DirectMessage.NewFromJsonDict(x) for x in data]
def PostDirectMessage(self,
text,
user_id=None,
screen_name=None):
"""Post a twitter direct message from the authenticated user.
Args:
text: The message text to be posted. Must be less than 140 characters.
user_id:
The ID of the user who should receive the direct message. [Optional]
screen_name:
The screen name of the user who should receive the direct message. [Optional]
Returns:
A twitter.DirectMessage instance representing the message posted
"""
url = '%s/direct_messages/new.json' % self.base_url
data = {'text': text}
if user_id:
data['user_id'] = user_id
elif screen_name:
data['screen_name'] = screen_name
else:
raise TwitterError({'message': "Specify at least one of user_id or screen_name."})
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return DirectMessage.NewFromJsonDict(data)
def DestroyDirectMessage(self, message_id, include_entities=True):
"""Destroys the direct message specified in the required ID parameter.
The twitter.Api instance must be authenticated, and the
authenticating user must be the recipient of the specified direct
message.
Args:
message_id: The id of the direct message to be destroyed
Returns:
A twitter.DirectMessage instance representing the message destroyed
"""
url = '%s/direct_messages/destroy.json' % self.base_url
data = {
'id': enf_type('message_id', int, message_id),
'include_entities': enf_type('include_entities', bool, include_entities)
}
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return DirectMessage.NewFromJsonDict(data)
def CreateFriendship(self, user_id=None, screen_name=None, follow=True):
"""Befriends the user specified by the user_id or screen_name.
Args:
user_id:
A user_id to follow [Optional]
screen_name:
A screen_name to follow [Optional]
follow:
Set to False to disable notifications for the target user
Returns:
A twitter.User instance representing the befriended user.
"""
return self._AddOrEditFriendship(user_id=user_id, screen_name=screen_name, follow=follow)
def _AddOrEditFriendship(self, user_id=None, screen_name=None, uri_end='create', follow_key='follow', follow=True):
"""
Shared method for Create/Update Friendship.
"""
url = '%s/friendships/%s.json' % (self.base_url, uri_end)
data = {}
if user_id:
data['user_id'] = user_id
elif screen_name:
data['screen_name'] = screen_name
else:
raise TwitterError({'message': "Specify at least one of user_id or screen_name."})
follow_json = json.dumps(follow)
data['{}'.format(follow_key)] = follow_json
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def UpdateFriendship(self, user_id=None, screen_name=None, follow=True, **kwargs): # api compat with Create
"""Updates a friendship with the user specified by the user_id or screen_name.
Args:
user_id:
A user_id to update [Optional]
screen_name:
A screen_name to update [Optional]
follow:
Set to False to disable notifications for the target user
device:
Set to False to disable notifications for the target user
Returns:
A twitter.User instance representing the befriended user.
"""
follow = kwargs.get('device', follow)
return self._AddOrEditFriendship(user_id=user_id, screen_name=screen_name, follow=follow, follow_key='device',
uri_end='update')
def DestroyFriendship(self, user_id=None, screen_name=None):
"""Discontinues friendship with a user_id or screen_name.
Args:
user_id:
A user_id to unfollow [Optional]
screen_name:
A screen_name to unfollow [Optional]
Returns:
A twitter.User instance representing the discontinued friend.
"""
url = '%s/friendships/destroy.json' % self.base_url
data = {}
if user_id:
data['user_id'] = user_id
elif screen_name:
data['screen_name'] = screen_name
else:
raise TwitterError({'message': "Specify at least one of user_id or screen_name."})
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def ShowFriendship(self,
source_user_id=None,
source_screen_name=None,
target_user_id=None,
target_screen_name=None):
"""Returns information about the relationship between the two users.
Args:
source_id:
The user_id of the subject user [Optional]
source_screen_name:
The screen_name of the subject user [Optional]
target_id:
The user_id of the target user [Optional]
target_screen_name:
The screen_name of the target user [Optional]
Returns:
A Twitter Json structure.
"""
url = '%s/friendships/show.json' % self.base_url
data = {}
if source_user_id:
data['source_id'] = source_user_id
elif source_screen_name:
data['source_screen_name'] = source_screen_name
else:
raise TwitterError({'message': "Specify at least one of source_user_id or source_screen_name."})
if target_user_id:
data['target_id'] = target_user_id
elif target_screen_name:
data['target_screen_name'] = target_screen_name
else:
raise TwitterError({'message': "Specify at least one of target_user_id or target_screen_name."})
resp = self._RequestUrl(url, 'GET', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data
def LookupFriendship(self,
user_id=None,
screen_name=None):
"""Lookup friendship status for user to authed user.
Users may be specified either as lists of either user_ids,
screen_names, or twitter.User objects. The list of users that
are queried is the union of all specified parameters.
Up to 100 users may be specified.
Args:
user_id (int, User, or list of ints or Users, optional):
A list of user_ids to retrieve extended information.
screen_name (string, User, or list of strings or Users, optional):
A list of screen_names to retrieve extended information.
Returns:
list: A list of twitter.UserStatus instance representing the
friendship status between the specified users and the authenticated
user.
"""
url = '%s/friendships/lookup.json' % (self.base_url)
parameters = {}
if user_id:
if isinstance(user_id, list) or isinstance(user_id, tuple):
uids = list()
for user in user_id:
if isinstance(user, User):
uids.append(user.id)
else:
uids.append(enf_type('user_id', int, user))
parameters['user_id'] = ",".join([str(uid) for uid in uids])
else:
if isinstance(user_id, User):
parameters['user_id'] = user_id.id
else:
parameters['user_id'] = enf_type('user_id', int, user_id)
if screen_name:
if isinstance(screen_name, list) or isinstance(screen_name, tuple):
sn_list = list()
for user in screen_name:
if isinstance(user, User):
sn_list.append(user.screen_name)
else:
sn_list.append(enf_type('screen_name', str, user))
parameters['screen_name'] = ','.join(sn_list)
else:
if isinstance(screen_name, User):
parameters['screen_name'] = screen_name.screen_name
else:
parameters['screen_name'] = enf_type('screen_name', str, screen_name)
if not user_id and not screen_name:
raise TwitterError(
"Specify at least one of user_id or screen_name.")
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [UserStatus.NewFromJsonDict(x) for x in data]
def IncomingFriendship(self,
cursor=None,
stringify_ids=None):
"""Returns a collection of user IDs belonging to users who have
pending request to follow the authenticated user.
Args:
cursor:
breaks the ids into pages of no more than 5000.
stringify_ids:
returns the IDs as unicode strings. [Optional]
Returns:
A list of user IDs
"""
url = '%s/friendships/incoming.json' % (self.base_url)
parameters = {}
if stringify_ids:
parameters['stringify_ids'] = 'true'
result = []
total_count = 0
while True:
if cursor:
try:
parameters['count'] = int(cursor)
except ValueError:
raise TwitterError({'message': "cursor must be an integer"})
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
result += [x for x in data['ids']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
total_count -= len(data['ids'])
if total_count < 1:
break
else:
break
return result
def OutgoingFriendship(self,
cursor=None,
stringify_ids=None):
"""Returns a collection of user IDs for every protected user
for whom the authenticated user has a pending follow request.
Args:
cursor:
breaks the ids into pages of no more than 5000.
stringify_ids:
returns the IDs as unicode strings. [Optional]
Returns:
A list of user IDs
"""
url = '%s/friendships/outgoing.json' % (self.base_url)
parameters = {}
if stringify_ids:
parameters['stringify_ids'] = 'true'
result = []
total_count = 0
while True:
if cursor:
try:
parameters['count'] = int(cursor)
except ValueError:
raise TwitterError({'message': "cursor must be an integer"})
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
result += [x for x in data['ids']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
total_count -= len(data['ids'])
if total_count < 1:
break
else:
break
return result
def CreateFavorite(self,
status=None,
status_id=None,
include_entities=True):
"""Favorites the specified status object or id as the authenticating user.
Returns the favorite status when successful.
Args:
status_id (int, optional):
The id of the twitter status to mark as a favorite.
status (twitter.Status, optional):
The twitter.Status object to mark as a favorite.
include_entities (bool, optional):
The entities node will be omitted when set to False.
Returns:
A twitter.Status instance representing the newly-marked favorite.
"""
url = '%s/favorites/create.json' % self.base_url
data = {}
if status_id:
data['id'] = status_id
elif status:
data['id'] = status.id
else:
raise TwitterError({'message': "Specify status_id or status"})
data['include_entities'] = enf_type('include_entities', bool, include_entities)
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def DestroyFavorite(self,
status=None,
status_id=None,
include_entities=True):
"""Un-Favorites the specified status object or id as the authenticating user.
Returns the un-favorited status when successful.
Args:
status_id (int, optional):
The id of the twitter status to mark as a favorite.
status (twitter.Status, optional):
The twitter.Status object to mark as a favorite.
include_entities (bool, optional):
The entities node will be omitted when set to False.
Returns:
A twitter.Status instance representing the newly-unmarked favorite.
"""
url = '%s/favorites/destroy.json' % self.base_url
data = {}
if status_id:
data['id'] = status_id
elif status:
data['id'] = status.id
else:
raise TwitterError({'message': "Specify status_id or status"})
data['include_entities'] = enf_type('include_entities', bool, include_entities)
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return Status.NewFromJsonDict(data)
def GetFavorites(self,
user_id=None,
screen_name=None,
count=None,
since_id=None,
max_id=None,
include_entities=True):
"""Return a list of Status objects representing favorited tweets.
Returns up to 200 most recent tweets for the authenticated user.
Args:
user_id (int, optional):
Specifies the ID of the user for whom to return the
favorites. Helpful for disambiguating when a valid user ID
is also a valid screen name.
screen_name (str, optional):
Specifies the screen name of the user for whom to return the
favorites. Helpful for disambiguating when a valid screen
name is also a user ID.
since_id (int, optional):
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available.
max_id (int, optional):
Returns only statuses with an ID less than (that is, older
than) or equal to the specified ID.
count (int, optional):
Specifies the number of statuses to retrieve. May not be
greater than 200.
include_entities (bool, optional):
The entities node will be omitted when set to False.
Returns:
A sequence of Status instances, one for each favorited tweet up to count
"""
parameters = {}
url = '%s/favorites/list.json' % self.base_url
if user_id:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
parameters['screen_name'] = screen_name
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if count:
parameters['count'] = enf_type('count', int, count)
parameters['include_entities'] = enf_type('include_entities', bool, include_entities)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data]
def GetMentions(self,
count=None,
since_id=None,
max_id=None,
trim_user=False,
contributor_details=False,
include_entities=True):
"""Returns the 20 most recent mentions (status containing @screen_name)
for the authenticating user.
Args:
count:
Specifies the number of tweets to try and retrieve, up to a maximum of
200. The value of count is best thought of as a limit to the number of
tweets to return because suspended or deleted content is removed after
the count has been applied. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns only statuses with an ID less than
(that is, older than) the specified ID. [Optional]
trim_user:
When set to True, each tweet returned in a timeline will include a user
object including only the status authors numerical ID. Omit this
parameter to receive the complete user object. [Optional]
contributor_details:
If set to True, this parameter enhances the contributors element of the
status response to include the screen_name of the contributor. By
default only the user_id of the contributor is included. [Optional]
include_entities:
The entities node will be disincluded when set to False. [Optional]
Returns:
A sequence of twitter.Status instances, one for each mention of the user.
"""
url = '%s/statuses/mentions_timeline.json' % self.base_url
parameters = {}
if count:
parameters['count'] = enf_type('count', int, count)
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if trim_user:
parameters['trim_user'] = 1
if contributor_details:
parameters['contributor_details'] = 'true'
if not include_entities:
parameters['include_entities'] = 'false'
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data]
@staticmethod
def _IDList(list_id, slug, owner_id, owner_screen_name):
parameters = {}
if list_id is not None:
parameters['list_id'] = enf_type('list_id', int, list_id)
elif slug is not None:
parameters['slug'] = slug
if owner_id is not None:
parameters['owner_id'] = enf_type('owner_id', int, owner_id)
elif owner_screen_name is not None:
parameters['owner_screen_name'] = owner_screen_name
else:
raise TwitterError({'message': (
'If specifying a list by slug, an owner_id or '
'owner_screen_name must also be given.')})
else:
raise TwitterError({'message': (
'Either list_id or slug and one of owner_id and '
'owner_screen_name must be passed.')})
return parameters
def CreateList(self, name, mode=None, description=None):
"""Creates a new list with the give name for the authenticated user.
Args:
name (str):
New name for the list
mode (str, optional):
'public' or 'private'. Defaults to 'public'.
description (str, optional):
Description of the list.
Returns:
twitter.list.List: A twitter.List instance representing the new list
"""
url = '%s/lists/create.json' % self.base_url
parameters = {'name': name}
if mode is not None:
parameters['mode'] = mode
if description is not None:
parameters['description'] = description
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return List.NewFromJsonDict(data)
def DestroyList(self,
owner_screen_name=None,
owner_id=None,
list_id=None,
slug=None):
"""Destroys the list identified by list_id or slug and one of
owner_screen_name or owner_id.
Args:
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested
by a slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested
by a slug.
list_id (int, optional):
The numerical id of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical id.
If you decide to do so, note that you'll also have to specify
the list owner using the owner_id or owner_screen_name parameters.
Returns:
twitter.list.List: A twitter.List instance representing the
removed list.
"""
url = '%s/lists/destroy.json' % self.base_url
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return List.NewFromJsonDict(data)
def CreateSubscription(self,
owner_screen_name=None,
owner_id=None,
list_id=None,
slug=None):
"""Creates a subscription to a list by the authenticated user.
Args:
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested
by a slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested
by a slug.
list_id (int, optional):
The numerical id of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical id.
If you decide to do so, note that you'll also have to specify
the list owner using the owner_id or owner_screen_name parameters.
Returns:
twitter.user.User: A twitter.User instance representing the user subscribed
"""
url = '%s/lists/subscribers/create.json' % self.base_url
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def DestroySubscription(self,
owner_screen_name=None,
owner_id=None,
list_id=None,
slug=None):
"""Destroys the subscription to a list for the authenticated user.
Args:
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested
by a slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested
by a slug.
list_id (int, optional):
The numerical id of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical id.
If you decide to do so, note that you'll also have to specify the
list owner using the owner_id or owner_screen_name parameters.
Returns:
twitter.list.List: A twitter.List instance representing
the removed list.
"""
url = '%s/lists/subscribers/destroy.json' % (self.base_url)
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return List.NewFromJsonDict(data)
def ShowSubscription(self,
owner_screen_name=None,
owner_id=None,
list_id=None,
slug=None,
user_id=None,
screen_name=None,
include_entities=False,
skip_status=False):
"""Check if the specified user is a subscriber of the specified list.
Returns the user if they are subscriber.
Args:
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested
by a slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested
by a slug.
list_id (int, optional):
The numerical ID of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical ID.
If you decide to do so, note that you'll also have to specify
the list owner using the owner_id or owner_screen_name parameters.
user_id (int, optional):
The user_id or a list of user_id's to add to the list.
If not given, then screen_name is required.
screen_name (str, optional):
The screen_name or a list of screen_name's to add to the list.
If not given, then user_id is required.
include_entities (bool, optional):
If False, the timeline will not contain additional metadata.
Defaults to True.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
Returns:
twitter.user.User: A twitter.User instance representing the user
requested.
"""
url = '%s/lists/subscribers/show.json' % (self.base_url)
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
if user_id:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
parameters['screen_name'] = screen_name
if skip_status:
parameters['skip_status'] = True
if include_entities:
parameters['include_entities'] = True
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def GetSubscriptions(self,
user_id=None,
screen_name=None,
count=20,
cursor=-1):
"""Obtain a collection of the lists the specified user is
subscribed to. If neither user_id or screen_name is specified, the
data returned will be for the authenticated user.
The list will contain a maximum of 20 lists per page by default.
Does not include the user's own lists.
Args:
user_id (int, optional):
The ID of the user for whom to return results for.
screen_name (str, optional):
The screen name of the user for whom to return results for.
count (int, optional):
The amount of results to return per page.
No more than 1000 results will ever be returned in a single
page. Defaults to 20.
cursor (int, optional):
The "page" value that Twitter will use to start building the
list sequence from. Use the value of -1 to start at the
beginning. Twitter will return in the result the values for
next_cursor and previous_cursor.
Returns:
twitter.list.List: A sequence of twitter.List instances,
one for each list
"""
url = '%s/lists/subscriptions.json' % (self.base_url)
parameters = {}
parameters['cursor'] = enf_type('cursor', int, cursor)
parameters['count'] = enf_type('count', int, count)
if user_id is not None:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name is not None:
parameters['screen_name'] = screen_name
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [List.NewFromJsonDict(x) for x in data['lists']]
def GetMemberships(self,
user_id=None,
screen_name=None,
count=20,
cursor=-1,
filter_to_owned_lists=False):
"""Obtain the lists the specified user is a member of. If no user_id or
screen_name is specified, the data returned will be for the
authenticated user.
Returns a maximum of 20 lists per page by default.
Args:
user_id (int, optional):
The ID of the user for whom to return results for.
screen_name (str, optional):
The screen name of the user for whom to return
results for.
count (int, optional):
The amount of results to return per page.
No more than 1000 results will ever be returned in a single page.
Defaults to 20.
cursor (int, optional):
The "page" value that Twitter will use to start building the list
sequence from. Use the value of -1 to start at the beginning.
Twitter will return in the result the values for next_cursor and
previous_cursor.
filter_to_owned_lists (bool, optional):
Set to True to return only the lists the authenticating user
owns, and the user specified by user_id or screen_name is a
member of. Default value is False.
Returns:
list: A list of twitter.List instances, one for each list in which
the user specified by user_id or screen_name is a member
"""
url = '%s/lists/memberships.json' % (self.base_url)
parameters = {}
if cursor is not None:
parameters['cursor'] = enf_type('cursor', int, cursor)
if count is not None:
parameters['count'] = enf_type('count', int, count)
if filter_to_owned_lists:
parameters['filter_to_owned_lists'] = enf_type(
'filter_to_owned_lists', bool, filter_to_owned_lists)
if user_id is not None:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name is not None:
parameters['screen_name'] = screen_name
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [List.NewFromJsonDict(x) for x in data['lists']]
def GetListsList(self,
screen_name=None,
user_id=None,
reverse=False):
"""Returns all lists the user subscribes to, including their own.
If no user_id or screen_name is specified, the data returned will be
for the authenticated user.
Args:
screen_name (str, optional):
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID.
user_id (int, optional):
Specifies the ID of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
reverse (bool, optional):
If False, the owned lists will be returned first, othewise
subscribed lists will be at the top. Returns a maximum of 100
entries regardless. Defaults to False.
Returns:
list: A sequence of twitter.List instances.
"""
url = '%s/lists/list.json' % (self.base_url)
parameters = {}
if user_id:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
parameters['screen_name'] = screen_name
if reverse:
parameters['reverse'] = enf_type('reverse', bool, reverse)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [List.NewFromJsonDict(x) for x in data]
def GetListTimeline(self,
list_id=None,
slug=None,
owner_id=None,
owner_screen_name=None,
since_id=None,
max_id=None,
count=None,
include_rts=True,
include_entities=True):
"""Fetch the sequence of Status messages for a given List ID.
Args:
list_id (int, optional):
Specifies the ID of the list to retrieve.
slug (str, optional):
The slug name for the list to retrieve. If you specify None for the
list_id, then you have to provide either a owner_screen_name or
owner_id.
owner_id (int, optional):
Specifies the ID of the user for whom to return the
list timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
owner_screen_name (str, optional):
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID.
since_id (int, optional):
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API.
If the limit of Tweets has occurred since the since_id, the
since_id will be forced to the oldest ID available.
max_id (int, optional):
Returns only statuses with an ID less than (that is, older than) or
equal to the specified ID.
count (int, optional):
Specifies the number of statuses to retrieve.
May not be greater than 200.
include_rts (bool, optional):
If True, the timeline will contain native retweets (if they exist)
in addition to the standard stream of tweets.
include_entities (bool, optional):
If False, the timeline will not contain additional metadata.
Defaults to True.
Returns:
list: A list of twitter.status.Status instances, one for each
message up to count.
"""
url = '%s/lists/statuses.json' % self.base_url
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
if since_id:
parameters['since_id'] = enf_type('since_id', int, since_id)
if max_id:
parameters['max_id'] = enf_type('max_id', int, max_id)
if count:
parameters['count'] = enf_type('count', int, count)
if not include_rts:
parameters['include_rts'] = enf_type('include_rts', bool, include_rts)
if not include_entities:
parameters['include_entities'] = enf_type('include_entities', bool, include_entities)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return [Status.NewFromJsonDict(x) for x in data]
def GetListMembersPaged(self,
list_id=None,
slug=None,
owner_id=None,
owner_screen_name=None,
cursor=-1,
count=100,
skip_status=False,
include_entities=True):
"""Fetch the sequence of twitter.User instances, one for each member
of the given list_id or slug.
Args:
list_id (int, optional):
Specifies the ID of the list to retrieve.
slug (str, optional):
The slug name for the list to retrieve. If you specify None for the
list_id, then you have to provide either a owner_screen_name or
owner_id.
owner_id (int, optional):
Specifies the ID of the user for whom to return the
list timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
owner_screen_name (str, optional):
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID.
cursor (int, optional):
Should be set to -1 for the initial call and then is used to
control what result page Twitter returns.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
If False, the timeline will not contain additional metadata.
Defaults to True.
Returns:
list: A sequence of twitter.user.User instances, one for each
member of the twitter.list.List.
"""
url = '%s/lists/members.json' % self.base_url
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
if count:
parameters['count'] = enf_type('count', int, count)
if cursor:
parameters['cursor'] = enf_type('cursor', int, cursor)
parameters['skip_status'] = enf_type('skip_status', bool, skip_status)
parameters['include_entities'] = enf_type('include_entities', bool, include_entities)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
next_cursor = data.get('next_cursor', 0)
previous_cursor = data.get('previous_cursor', 0)
users = [User.NewFromJsonDict(user) for user in data.get('users', [])]
return next_cursor, previous_cursor, users
def GetListMembers(self,
list_id=None,
slug=None,
owner_id=None,
owner_screen_name=None,
skip_status=False,
include_entities=False):
"""Fetch the sequence of twitter.User instances, one for each member
of the given list_id or slug.
Args:
list_id (int, optional):
Specifies the ID of the list to retrieve.
slug (str, optional):
The slug name for the list to retrieve. If you specify None for the
list_id, then you have to provide either a owner_screen_name or
owner_id.
owner_id (int, optional):
Specifies the ID of the user for whom to return the
list timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name.
owner_screen_name (str, optional):
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID.
skip_status (bool, optional):
If True the statuses will not be returned in the user items.
include_entities (bool, optional):
If False, the timeline will not contain additional metadata.
Defaults to True.
Returns:
list: A sequence of twitter.user.User instances, one for each
member of the twitter.list.List.
"""
cursor = -1
result = []
while True:
next_cursor, previous_cursor, users = self.GetListMembersPaged(
list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name,
cursor=cursor,
skip_status=skip_status,
include_entities=include_entities)
result += users
if next_cursor == 0 or next_cursor == previous_cursor:
break
else:
cursor = next_cursor
return result
def CreateListsMember(self,
list_id=None,
slug=None,
user_id=None,
screen_name=None,
owner_screen_name=None,
owner_id=None):
"""Add a new member (or list of members) to the specified list.
Args:
list_id (int, optional):
The numerical id of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical id.
If you decide to do so, note that you'll also have to specify the
list owner using the owner_id or owner_screen_name parameters.
user_id (int, optional):
The user_id or a list of user_id's to add to the list.
If not given, then screen_name is required.
screen_name (str, optional):
The screen_name or a list of screen_name's to add to the list.
If not given, then user_id is required.
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested by
a slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested by
a slug.
Returns:
twitter.list.List: A twitter.List instance representing the list
subscribed to.
"""
is_list = False
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
if user_id:
if isinstance(user_id, list) or isinstance(user_id, tuple):
is_list = True
uids = [str(enf_type('user_id', int, uid)) for uid in user_id]
parameters['user_id'] = ','.join(uids)
else:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name:
if isinstance(screen_name, list) or isinstance(screen_name, tuple):
is_list = True
parameters['screen_name'] = ','.join(screen_name)
else:
parameters['screen_name'] = screen_name
if is_list:
url = '%s/lists/members/create_all.json' % self.base_url
else:
url = '%s/lists/members/create.json' % self.base_url
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return List.NewFromJsonDict(data)
def DestroyListsMember(self,
list_id=None,
slug=None,
owner_screen_name=None,
owner_id=None,
user_id=None,
screen_name=None):
"""Destroys the subscription to a list for the authenticated user.
Args:
list_id (int, optional):
The numerical id of the list.
slug (str, optional):
You can identify a list by its slug instead of its numerical id.
If you decide to do so, note that you'll also have to specify
the list owner using the owner_id or owner_screen_name parameters.
owner_screen_name (str, optional):
The screen_name of the user who owns the list being requested by a
slug.
owner_id (int, optional):
The user ID of the user who owns the list being requested by a slug.
user_id (int, optional):
The user_id or a list of user_id's to remove from the list.
If not given, then screen_name is required.
screen_name (str, optional):
The screen_name or a list of Screen_name's to remove from the list.
If not given, then user_id is required.
Returns:
twitter.list.List: A twitter.List instance representing the
removed list.
"""
is_list = False
parameters = {}
parameters.update(self._IDList(list_id=list_id,
slug=slug,
owner_id=owner_id,
owner_screen_name=owner_screen_name))
if user_id:
if isinstance(user_id, list) or isinstance(user_id, tuple):
is_list = True
uids = [str(enf_type('user_id', int, uid)) for uid in user_id]
parameters['user_id'] = ','.join(uids)
else:
parameters['user_id'] = int(user_id)
elif screen_name:
if isinstance(screen_name, list) or isinstance(screen_name, tuple):
is_list = True
parameters['screen_name'] = ','.join(screen_name)
else:
parameters['screen_name'] = screen_name
if is_list:
url = '%s/lists/members/destroy_all.json' % self.base_url
else:
url = '%s/lists/members/destroy.json' % self.base_url
resp = self._RequestUrl(url, 'POST', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return List.NewFromJsonDict(data)
def GetListsPaged(self,
user_id=None,
screen_name=None,
cursor=-1,
count=20):
""" Fetch the sequence of lists for a user. If no user_id or
screen_name is passed, the data returned will be for the
authenticated user.
Args:
user_id (int, optional):
The ID of the user for whom to return results for.
screen_name (str, optional):
The screen name of the user for whom to return results
for.
count (int, optional):
The amount of results to return per page. No more than 1000 results
will ever be returned in a single page. Defaults to 20.
cursor (int, optional):
The "page" value that Twitter will use to start building the list
sequence from. Use the value of -1 to start at the beginning.
Twitter will return in the result the values for next_cursor and
previous_cursor.
Returns:
next_cursor (int), previous_cursor (int), list of twitter.List
instances, one for each list
"""
url = '%s/lists/ownerships.json' % self.base_url
parameters = {}
if user_id is not None:
parameters['user_id'] = enf_type('user_id', int, user_id)
elif screen_name is not None:
parameters['screen_name'] = screen_name
if count is not None:
parameters['count'] = enf_type('count', int, count)
parameters['cursor'] = enf_type('cursor', int, cursor)
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
next_cursor = data.get('next_cursor', 0)
previous_cursor = data.get('previous_cursor', 0)
lists = [List.NewFromJsonDict(x) for x in data.get('lists', [])]
return next_cursor, previous_cursor, lists
def GetLists(self,
user_id=None,
screen_name=None):
"""Fetch the sequence of lists for a user. If no user_id or screen_name
is passed, the data returned will be for the authenticated user.
Args:
user_id:
The ID of the user for whom to return results for. [Optional]
screen_name:
The screen name of the user for whom to return results
for. [Optional]
count:
The amount of results to return per page.
No more than 1000 results will ever be returned in a single page.
Defaults to 20. [Optional]
cursor:
The "page" value that Twitter will use to start building the list
sequence from. Use the value of -1 to start at the beginning.
Twitter will return in the result the values for next_cursor and
previous_cursor. [Optional]
Returns:
A sequence of twitter.List instances, one for each list
"""
result = []
cursor = -1
while True:
next_cursor, prev_cursor, lists = self.GetListsPaged(
user_id=user_id,
screen_name=screen_name,
cursor=cursor)
result += lists
if next_cursor == 0 or next_cursor == prev_cursor:
break
else:
cursor = next_cursor
return result
def UpdateProfile(self,
name=None,
profileURL=None,
location=None,
description=None,
profile_link_color=None,
include_entities=False,
skip_status=False):
"""Update's the authenticated user's profile data.
Args:
name:
Full name associated with the profile.
Maximum of 20 characters. [Optional]
profileURL:
URL associated with the profile.
Will be prepended with "http://" if not present.
Maximum of 100 characters. [Optional]
location:
The city or country describing where the user of the account is located.
The contents are not normalized or geocoded in any way.
Maximum of 30 characters. [Optional]
description:
A description of the user owning the account.
Maximum of 160 characters. [Optional]
profile_link_color:
hex value of profile color theme. formated without '#' or '0x'. Ex: FF00FF
[Optional]
include_entities:
The entities node will be omitted when set to False.
[Optional]
skip_status:
When set to either True, t or 1 then statuses will not be included
in the returned user objects. [Optional]
Returns:
A twitter.User instance representing the modified user.
"""
url = '%s/account/update_profile.json' % (self.base_url)
data = {}
if name:
data['name'] = name
if profileURL:
data['url'] = profileURL
if location:
data['location'] = location
if description:
data['description'] = description
if profile_link_color:
data['profile_link_color'] = profile_link_color
if include_entities:
data['include_entities'] = include_entities
if skip_status:
data['skip_status'] = skip_status
resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def UpdateBackgroundImage(self,
image,
tile=False,
include_entities=False,
skip_status=False):
"""Deprecated function. Used to update the background of a User's
Twitter profile. Removed in approx. July, 2015"""
warnings.warn((
"This method has been deprecated by Twitter as of July 2015 and "
"will be removed in future versions of python-twitter."),
PythonTwitterDeprecationWarning330)
url = '%s/account/update_profile_background_image.json' % (self.base_url)
with open(image, 'rb') as image_file:
encoded_image = base64.b64encode(image_file.read())
data = {
'image': encoded_image
}
if tile:
data['tile'] = 1
if include_entities:
data['include_entities'] = 1
if skip_status:
data['skip_status'] = 1
resp = self._RequestUrl(url, 'POST', data=data)
if resp.status_code in [200, 201, 202]:
return True
if resp.status_code == 400:
raise TwitterError({'message': "Image data could not be processed"})
if resp.status_code == 422:
raise TwitterError({'message': "The image could not be resized or is too large."})
def UpdateImage(self,
image,
include_entities=False,
skip_status=False):
"""Update a User's profile image. Change may not be immediately
reflected due to image processing on Twitter's side.
Args:
image (str):
Location of local image file to use.
include_entities (bool, optional):
Include the entities node in the return data.
skip_status (bool, optional):
Include the User's last Status in the User entity returned.
Returns:
(twitter.models.User): Updated User object.
"""
url = '%s/account/update_profile_image.json' % (self.base_url)
with open(image, 'rb') as image_file:
encoded_image = base64.b64encode(image_file.read())
data = {
'image': encoded_image
}
if include_entities:
data['include_entities'] = 1
if skip_status:
data['skip_status'] = 1
resp = self._RequestUrl(url, 'POST', data=data)
if resp.status_code in [200, 201, 202]:
return True
if resp.status_code == 400:
raise TwitterError({'message': "Image data could not be processed"})
if resp.status_code == 422:
raise TwitterError({'message': "The image could not be resized or is too large."})
def UpdateBanner(self,
image,
include_entities=False,
skip_status=False):
"""Updates the authenticated users profile banner.
Args:
image:
Location of image in file system
include_entities:
If True, each tweet will include a node called "entities."
This node offers a variety of metadata about the tweet in a
discrete structure, including: user_mentions, urls, and hashtags.
[Optional]
Returns:
A twitter.List instance representing the list subscribed to
"""
url = '%s/account/update_profile_banner.json' % (self.base_url)
with open(image, 'rb') as image_file:
encoded_image = base64.b64encode(image_file.read())
data = {
# When updated for API v1.1 use image, not banner
# https://dev.twitter.com/docs/api/1.1/post/account/update_profile_banner
# 'image': encoded_image
'banner': encoded_image
}
if include_entities:
data['include_entities'] = 1
if skip_status:
data['skip_status'] = 1
resp = self._RequestUrl(url, 'POST', data=data)
if resp.status_code in [200, 201, 202]:
return True
if resp.status_code == 400:
raise TwitterError({'message': "Image data could not be processed"})
if resp.status_code == 422:
raise TwitterError({'message': "The image could not be resized or is too large."})
raise TwitterError({'message': "Unkown banner image upload issue"})
def GetStreamSample(self, delimited=False, stall_warnings=True):
"""Returns a small sample of public statuses.
Args:
delimited:
Specifies a message length. [Optional]
stall_warnings:
Set to True to have Twitter deliver stall warnings. [Optional]
Returns:
A Twitter stream
"""
url = '%s/statuses/sample.json' % self.stream_url
parameters = {
'delimited': bool(delimited),
'stall_warnings': bool(stall_warnings)
}
resp = self._RequestStream(url, 'GET', data=parameters)
for line in resp.iter_lines():
if line:
data = self._ParseAndCheckTwitter(line.decode('utf-8'))
yield data
def GetStreamFilter(self,
follow=None,
track=None,
locations=None,
languages=None,
delimited=None,
stall_warnings=None,
filter_level=None):
"""Returns a filtered view of public statuses.
Args:
follow:
A list of user IDs to track. [Optional]
track:
A list of expressions to track. [Optional]
locations:
A list of Longitude,Latitude pairs (as strings) specifying
bounding boxes for the tweets' origin. [Optional]
delimited:
Specifies a message length. [Optional]
stall_warnings:
Set to True to have Twitter deliver stall warnings. [Optional]
languages:
A list of Languages.
Will only return Tweets that have been detected as being
written in the specified languages. [Optional]
filter_level:
Specifies level of filtering applied to stream.
Set to None, 'low' or 'medium'. [Optional]
Returns:
A twitter stream
"""
if all((follow is None, track is None, locations is None)):
raise ValueError({'message': "No filter parameters specified."})
url = '%s/statuses/filter.json' % self.stream_url
data = {}
if follow is not None:
data['follow'] = ','.join(follow)
if track is not None:
data['track'] = ','.join(track)
if locations is not None:
data['locations'] = ','.join(locations)
if delimited is not None:
data['delimited'] = str(delimited)
if stall_warnings is not None:
data['stall_warnings'] = str(stall_warnings)
if languages is not None:
data['language'] = ','.join(languages)
if filter_level is not None:
data['filter_level'] = filter_level
resp = self._RequestStream(url, 'POST', data=data)
for line in resp.iter_lines():
if line:
data = self._ParseAndCheckTwitter(line.decode('utf-8'))
yield data
def GetUserStream(self,
replies='all',
withuser='user',
track=None,
locations=None,
delimited=None,
stall_warnings=None,
stringify_friend_ids=False,
filter_level=None):
"""Returns the data from the user stream.
Args:
replies:
Specifies whether to return additional @replies in the stream.
Defaults to 'all'.
withuser:
Specifies whether to return information for just the authenticating
user, or include messages from accounts the user follows. [Optional]
track:
A list of expressions to track. [Optional]
locations:
A list of Latitude,Longitude pairs (as strings) specifying
bounding boxes for the tweets' origin. [Optional]
delimited:
Specifies a message length. [Optional]
stall_warnings:
Set to True to have Twitter deliver stall warnings. [Optional]
stringify_friend_ids:
Specifies whether to send the friends list preamble as an array of
integers or an array of strings. [Optional]
filter_level:
Specifies level of filtering applied to stream.
Set to None, low or medium. [Optional]
Returns:
A twitter stream
"""
url = 'https://userstream.twitter.com/1.1/user.json'
data = {}
if stringify_friend_ids:
data['stringify_friend_ids'] = 'true'
if replies is not None:
data['replies'] = replies
if withuser is not None:
data['with'] = withuser
if track is not None:
data['track'] = ','.join(track)
if locations is not None:
data['locations'] = ','.join(locations)
if delimited is not None:
data['delimited'] = str(delimited)
if stall_warnings is not None:
data['stall_warnings'] = str(stall_warnings)
if filter_level is not None:
data['filter_level'] = filter_level
resp = self._RequestStream(url, 'POST', data=data)
for line in resp.iter_lines():
if line:
data = self._ParseAndCheckTwitter(line.decode('utf-8'))
yield data
def VerifyCredentials(self, include_entities=None, skip_status=None, include_email=None):
"""Returns a twitter.User instance if the authenticating user is valid.
Args:
include_entities:
Specifies whether to return additional @replies in the stream.
skip_status:
When set to either true, t or 1 statuses will not be included in the
returned user object.
include_email:
Use of this parameter requires whitelisting.
When set to true email will be returned in the user objects as a string.
If the user does not have an email address on their account, or if the
email address is un-verified, null will be returned. If your app is
not whitelisted, then the 'email' key will not be present in the json
response.
Returns:
A twitter.User instance representing that user if the
credentials are valid, None otherwise.
"""
url = '%s/account/verify_credentials.json' % self.base_url
data = {
'include_entities': enf_type('include_entities', bool, include_entities),
'skip_status': enf_type('skip_status', bool, skip_status),
'include_email': enf_type('include_email', bool, include_email)
}
resp = self._RequestUrl(url, 'GET', data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return User.NewFromJsonDict(data)
def SetCache(self, cache):
"""Override the default cache. Set to None to prevent caching.
Args:
cache:
An instance that supports the same API as the twitter._FileCache
"""
if cache == DEFAULT_CACHE:
self._cache = _FileCache()
else:
self._cache = cache
def SetUrllib(self, urllib):
"""Override the default urllib implementation.
Args:
urllib:
An instance that supports the same API as the urllib2 module
"""
self._urllib = urllib
def SetCacheTimeout(self, cache_timeout):
"""Override the default cache timeout.
Args:
cache_timeout:
Time, in seconds, that responses should be reused.
"""
self._cache_timeout = cache_timeout
def SetUserAgent(self, user_agent):
"""Override the default user agent.
Args:
user_agent:
A string that should be send to the server as the user-agent.
"""
self._request_headers['User-Agent'] = user_agent
def SetXTwitterHeaders(self, client, url, version):
"""Set the X-Twitter HTTP headers that will be sent to the server.
Args:
client:
The client name as a string. Will be sent to the server as
the 'X-Twitter-Client' header.
url:
The URL of the meta.xml as a string. Will be sent to the server
as the 'X-Twitter-Client-URL' header.
version:
The client version as a string. Will be sent to the server
as the 'X-Twitter-Client-Version' header.
"""
self._request_headers['X-Twitter-Client'] = client
self._request_headers['X-Twitter-Client-URL'] = url
self._request_headers['X-Twitter-Client-Version'] = version
def SetSource(self, source):
"""Suggest the "from source" value to be displayed on the Twitter web site.
The value of the 'source' parameter must be first recognized by
the Twitter server.
New source values are authorized on a case by case basis by the
Twitter development team.
Args:
source:
The source name as a string. Will be sent to the server as
the 'source' parameter.
"""
self._default_params['source'] = source
def InitializeRateLimit(self):
""" Make a call to the Twitter API to get the rate limit
status for the currently authenticated user or application.
Returns:
None.
"""
_sleep = self.sleep_on_rate_limit
if self.sleep_on_rate_limit:
self.sleep_on_rate_limit = False
url = '%s/application/rate_limit_status.json' % self.base_url
resp = self._RequestUrl(url, 'GET') # No-Cache
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
self.sleep_on_rate_limit = _sleep
self.rate_limit = RateLimit(**data)
def CheckRateLimit(self, url):
""" Checks a URL to see the rate limit status for that endpoint.
Args:
url (str):
URL to check against the current rate limits.
Returns:
namedtuple: EndpointRateLimit namedtuple.
"""
if not self.rate_limit.__dict__.get('resources', None):
self.InitializeRateLimit()
if url:
limit = self.rate_limit.get_limit(url)
return limit
def _BuildUrl(self, url, path_elements=None, extra_params=None):
# Break url into constituent parts
(scheme, netloc, path, params, query, fragment) = urlparse(url)
# Add any additional path elements to the path
if path_elements:
# Filter out the path elements that have a value of None
p = [i for i in path_elements if i]
if not path.endswith('/'):
path += '/'
path += '/'.join(p)
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
# Add it to the existing query
if query:
query += '&' + extra_query
else:
query = extra_query
# Return the rebuilt URL
return urlunparse((scheme, netloc, path, params, query, fragment))
def _InitializeRequestHeaders(self, request_headers):
if request_headers:
self._request_headers = request_headers
else:
self._request_headers = {}
def _InitializeUserAgent(self):
user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
(urllib_version, __version__)
self.SetUserAgent(user_agent)
def _InitializeDefaultParameters(self):
self._default_params = {}
@staticmethod
def _DecompressGzippedResponse(response):
raw_data = response.read()
if response.headers.get('content-encoding', None) == 'gzip':
url_data = gzip.GzipFile(fileobj=io.StringIO(raw_data)).read()
else:
url_data = raw_data
return url_data
@staticmethod
def _EncodeParameters(parameters):
"""Return a string in key=value&key=value form.
Values of None are not included in the output string.
Args:
parameters (dict): dictionary of query parameters to be converted into a
string for encoding and sending to Twitter.
Returns:
A URL-encoded string in "key=value&key=value" form
"""
if parameters is None:
return None
if not isinstance(parameters, dict):
raise TwitterError("`parameters` must be a dict.")
else:
return urlencode(dict((k, v) for k, v in parameters.items() if v is not None))
def _ParseAndCheckTwitter(self, json_data):
"""Try and parse the JSON returned from Twitter and return
an empty dictionary if there is any error.
This is a purely defensive check because during some Twitter
network outages it will return an HTML failwhale page.
"""
try:
data = json.loads(json_data)
except ValueError:
if "<title>Twitter / Over capacity</title>" in json_data:
raise TwitterError({'message': "Capacity Error"})
if "<title>Twitter / Error</title>" in json_data:
raise TwitterError({'message': "Technical Error"})
if "Exceeded connection limit for user" in json_data:
raise TwitterError({'message': "Exceeded connection limit for user"})
if "Error 401 Unauthorized" in json_data:
raise TwitterError({'message': "Unauthorized"})
raise TwitterError({'Unknown error: {0}'.format(json_data)})
self._CheckForTwitterError(data)
return data
@staticmethod
def _CheckForTwitterError(data):
"""Raises a TwitterError if twitter returns an error message.
Args:
data (dict):
A python dict created from the Twitter json response
Raises:
(twitter.TwitterError): TwitterError wrapping the twitter error
message if one exists.
"""
# Twitter errors are relatively unlikely, so it is faster
# to check first, rather than try and catch the exception
if 'error' in data:
raise TwitterError(data['error'])
if 'errors' in data:
raise TwitterError(data['errors'])
def _RequestChunkedUpload(self, url, headers, data):
try:
return requests.post(
url,
headers=headers,
data=data,
auth=self.__auth,
timeout=self._timeout,
proxies=self.proxies
)
except requests.RequestException as e:
raise TwitterError(str(e))
def _RequestUrl(self, url, verb, data=None, json=None, enforce_auth=True):
"""Request a url.
Args:
url:
The web location we want to retrieve.
verb:
Either POST or GET.
data:
A dict of (str, unicode) key/value pairs.
Returns:
A JSON object.
"""
if enforce_auth:
if not self.__auth:
raise TwitterError("The twitter.Api instance must be authenticated.")
if url and self.sleep_on_rate_limit:
limit = self.CheckRateLimit(url)
if limit.remaining == 0:
try:
time.sleep(max(int(limit.reset - time.time()) + 2, 0))
except ValueError:
pass
if not data:
data = {}
if verb == 'POST':
if data:
if 'media_ids' in data:
url = self._BuildUrl(url, extra_params={'media_ids': data['media_ids']})
resp = requests.post(url, data=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
elif 'media' in data:
resp = requests.post(url, files=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = requests.post(url, data=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
elif json:
resp = requests.post(url, json=json, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = 0 # POST request, but without data or json
elif verb == 'GET':
data['tweet_mode'] = self.tweet_mode
url = self._BuildUrl(url, extra_params=data)
resp = requests.get(url, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = 0 # if not a POST or GET request
if url and self.rate_limit:
limit = resp.headers.get('x-rate-limit-limit', 0)
remaining = resp.headers.get('x-rate-limit-remaining', 0)
reset = resp.headers.get('x-rate-limit-reset', 0)
self.rate_limit.set_limit(url, limit, remaining, reset)
return resp
def _RequestStream(self, url, verb, data=None):
"""Request a stream of data.
Args:
url:
The web location we want to retrieve.
verb:
Either POST or GET.
data:
A dict of (str, unicode) key/value pairs.
Returns:
A twitter stream.
"""
if verb == 'POST':
try:
return requests.post(url, data=data, stream=True,
auth=self.__auth,
timeout=self._timeout,
proxies=self.proxies)
except requests.RequestException as e:
raise TwitterError(str(e))
if verb == 'GET':
url = self._BuildUrl(url, extra_params=data)
try:
return requests.get(url, stream=True, auth=self.__auth,
timeout=self._timeout, proxies=self.proxies)
except requests.RequestException as e:
raise TwitterError(str(e))
return 0 # if not a POST or GET request
|