Al-Adab Al-Mufrad, Book 38, Hadith 2 (In-Book)

Muhammad ibn al-Hanafiyya said, "Not wise is he who does not deal correctly with a person whose company he cannot avoid until Allah appoints for him a release or a way out."

وَعَنِ الْحَسَنِ بْنِ عَمْرٍو الْفُقَيْمِيِّ، عَنْ مُنْذِرٍ الثَّوْرِيِّ، عَنْ مُحَمَّدِ ابْنِ الْحَنَفِيَّةِ قَالَ‏:‏ لَيْسَ بِحَكِيمٍ مَنْ لاَ يُعَاشِرُ بِالْمَعْرُوفِ مَنْ لاَ يَجِدُ مِنْ مُعَاشَرَتِهِ بُدًّا، حَتَّى يَجْعَلَ اللَّهُ لَهُ فَرَجًا أَوْ مَخْرَجًا‏.‏

sunnah.com